I'm new to cocos2d and I'm developing a game where identical objects (like Fruit Ninja) fall in continuous and the user must catch them both with a touch either by dragging the finger across the screen. I tried creating an NSMutableArray to which I add a sprite every time I create it and it falls down, but I realize that it detects that I touched a sprite even if it isn't true, seems that the sprite is invisible. when I touched the sprite I remove it, but it probably does not remove it. Here is my code:
@interface GameScene : CCScene
{
NSMutableArray *spriteArray;
}
- (id)init
{
spriteArray = [[NSMutableArray alloc]init];
return self;
}
- (void)onEnter
{
[super onEnter];
[self schedule:@selector(addSprites:) interval:1.0];
}
- (void)addSprites:(CCTime)dt
{
CCSprite *sprite = [CCSprite spriteWithImageNamed:@"sprite000.png"];
int minX = sprite.contentSize.width / 2;
int maxX = self.contentSize.width - sprite.contentSize.width / 2;
int rangeX = maxX - minX;
int randomX = (arc4random() % rangeX) + minX;
sprite.position = CGPointMake(randomX, self.contentSize.height + sprite.contentSize.height);
[self addChild:sprite z:6];
[spriteArray addObject:sprite];
CCAction *actionMove = [CCActionMoveTo actionWithDuration:3.0 position:CGPointMake(randomX, -sprite.contentSize.height)];
CCAction *actionRemove = [CCActionRemove action];
[sprite runAction:[CCActionSequence actionWithArray:@[actionMove, actionRemove]]];
if ([spriteArray count] > 50)
{
[spriteArray removeObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 40)]];
}
}
-(void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLoc = [touch locationInNode:self];
for (CCSprite *sprite in spriteArray)
{
if (CGRectContainsPoint([sprite boundingBox], touchLoc))
{
CCLOG(@"Touched!");
CCAction *actionRemove = [CCActionRemove action];
[sprite runAction:actionRemove];
return;
}
}
}
You are not removing the sprite from the spriteArray. So you will check for touches with the removed sprites, too. Try
for (int i=0;i<spriteArray.count;i++)
{
//get the current sprite from the array
CCSprite *sprite = [spriteArray objectAtIndex:i];
if (CGRectContainsPoint([sprite boundingBox], touchLoc))
{
CCLOG(@"Touched!");
CCAction *actionRemove = [CCActionRemove action];
[sprite runAction:actionRemove];
//remove the sprite from the array
[spriteArray removeObjectAtIndex:i];
//decrement i to be safe if you remove the return one day
--i;
return;
}
}