简体   繁体   中英

how to parse int in a for loop to a method in xcode?

Hi guys what I am trying to do is to create 6 sprites and to space them out evenly, I edited some code i got from a book, but am currently stuck at the part where I need to space the sprites out evenly

    [groundNode setPosition:CGPointMake(45, 20)];

where this will stack all 6 sprites on top of each other? How can I make it in such a way it would become something like

    [groundNode setPosition:CGPointMake(45*x, 20)];

where x is the int taken from the for loop. My code is listed at the bottom. Thank you so much!!

-(id)init{
    self = [super init];
    if(self !=nil){
        for(int x=0;x<6;x++){
            [self createGround];
        }   
    }
    return self;
}

-(void) createGround{
    int randomGround = arc4random()%3+1;
    NSString *groundName = [NSString stringWithFormat:@"ground%d.png", randomGround];
    CCSprite *groundSprite = [CCSprite spriteWithFile:groundName];
    [self addChild:groundSprite];
    [self resetGround:groundSprite];
}

-(void) resetGround:(id)node{
    CGSize screenSize =[CCDirector sharedDirector].winSize;
    CCNode *groundNode = (CCNode*)node;
    [groundNode setPosition:CGPointMake(45, 20)];

}

Step one is to build those methods to take an offsetIndex parameter:

-(void) createGroundWithOffsetIndex: (int) offsetIndex {
-(void) resetGround: (CCNode *) node withOffsetIndex: (int) offsetIndex {

Then, in createGround, pass it through:

[self resetGround:groundSprite withOffsetIndex: offsetIndex];

And pass it in from the loop:

for(int x=0;x<6;x++){
  [self createGroundWithOffsetIndex:x];
}       

And finally, the bit of code you knew you'd use (inside resetGround:withOffsetIndex:): (note the +1, since offsets (by semantic) start at zero)

[groundNode setPosition:CGPointMake(45 * offsetIndex+1, 20)];

Some notes:

  • Consider carefully how much passing is necessary here, and try to think of an improved architecture: if you are tiling the same image, perhaps createGround should take a CGRect and be responsible for filling that much area?

  • This is horizontal only; I leave it as an exercise to pass CGPoints (or similar {x,y} struct) as the offsetIndex.

  • Your casting patterns are borderline concerning. Why pass it as an id, then cast it into another local var, when the whole time it came in as yet another type? I'd think that one over...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM