I am a beginner in Cocos2d and I wanted to display 7 coins in a horizontal pattern. So this is what I wrote in my main gameplay layer:
In my init, I have this
coins = [CCSprite spriteWithFile:@"coins.png"];
I made a method for the coin patterns I want it to be in (display seven times across)
- (void)coinPatterns {
coins.position = ccp(150,150);
for(int i = 0; i < 7; i++)
{
coins.position = ccp (coins.position.x + 20, coins.position.y);
[self addChild:coins];
}
}
And then I added this in my update method
[self coinPatterns];
But for some reason, my code keeps crashing. Does anyone know how I can fix this?
Thanks!
I think what you want to do here is create a separate sprite node for each coin, instead of reusing the same one over and over (I'm not even sure if that works). You would do that like this
- (void)coinPatterns {
NSInteger originalX = 150;
for(int i = 0; i < 7; i++)
{
CCSprite *coin = [CCSprite spriteWithFile:@"coins.png"];
coin.position = ccp(originalX, 150);
originalX += 20;
[self addChild:coin];
}
}
This creates 7 coins, each spaced by 20. Also, in the code you provided, all 7 coins would have been stacked on top of each other, since the x
value was never actually incremented. If you use this, it's unnecessary to have the variable or property coins
.
If you want to access these coins later, for example to see if a character hit into them, you could make an NSMutableArray
property coinArray
and then to add each coin to the array add the line [self.coinArray addObject:coin];
to the for-loop under [self addChild:coin];
. That would put them all in the array.
To detect a collision, do something along the lines of this
- (void)characterMoved:(CCSprite *)character
{
for (CCSprite *coin in self.coinArray)
{
if (CGRectIntersectsRect(coin.frame, character.frame)
// character and coin collided, add points or remove the coin or something
}
}
This would need you to have a method characterMoved: that fires every time the character moves.