我是cocos2d的新手,我正在开发一个游戏,其中相同的物体(如水果忍者)连续落下,用户必须通过在屏幕上拖动手指来触摸它们。 我尝试创建一个NSMutableArray,每次创建它时我都会添加一个精灵然后它会掉下来,但我发现它检测到我触摸了一个精灵,即使它不是真的,似乎精灵是不可见的。 当我触摸精灵时,我将其删除,但它可能不会删除它。 这是我的代码:
@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;
}
}
}
答案 0 :(得分:1)
您没有从spriteArray中删除精灵。所以你也会检查被移除的精灵的触摸。尝试
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;
}
}