Ios 通过在屏幕上拖动手指检测CCSprite(包含在阵列中)的触摸
我是cocos2d新手,我正在开发一个游戏,在这个游戏中,相同的物体(如水果忍者)连续下落,用户必须通过触摸或者在屏幕上拖动手指来捕捉它们。 我尝试创建一个NSMutableArray,每次创建它时我都会向其中添加一个精灵,它会掉下来,但我意识到它检测到我触摸了一个精灵,即使它不是真的,似乎精灵是不可见的。 当我触摸精灵时,我将其移除,但它可能不会移除它。 这是我的密码:Ios 通过在屏幕上拖动手指检测CCSprite(包含在阵列中)的触摸,ios,objective-c,cocos2d-iphone,ccsprite,Ios,Objective C,Cocos2d Iphone,Ccsprite,我是cocos2d新手,我正在开发一个游戏,在这个游戏中,相同的物体(如水果忍者)连续下落,用户必须通过触摸或者在屏幕上拖动手指来捕捉它们。 我尝试创建一个NSMutableArray,每次创建它时我都会向其中添加一个精灵,它会掉下来,但我意识到它检测到我触摸了一个精灵,即使它不是真的,似乎精灵是不可见的。 当我触摸精灵时,我将其移除,但它可能不会移除它。 这是我的密码: @interface GameScene : CCScene { NSMutableArray *spriteArr
@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;
}
}
}
您没有从精灵阵列中移除精灵。所以你也要检查移除的精灵是否有触碰。试一试
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;
}
}
for(int i=0;i不客气!很高兴知道它现在已被弃用,所以我将其从我的答案中删除。