1

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)];

}

1 Answer 1

1

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...

1
  • Thank you so much! Yup I did realise that there was alot of unnecessary passing after editing the code, and have changed it. Commented Sep 15, 2012 at 6:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.