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:
Then, in createGround, pass it through:
And pass it in from the loop:
And finally, the bit of code you knew you’d use (inside resetGround:withOffsetIndex:): (note the +1, since offsets (by semantic) start at zero)
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…