gpt4 book ai didi

ios - 检测 CCSprite(包含在数组中)在屏幕上拖动手指的触摸

转载 作者:行者123 更新时间:2023-11-29 02:56:30 24 4
gpt4 key购买 nike

我是 cocos2d 的新手,我正在开发一款游戏,其中相同的对象(如水果忍者)连续落下,用户必须通过在屏幕上拖动手指来触摸它们。我尝试创建一个 NSMutableArray,每次创建它时都会向其添加一个 sprite,但它会掉下来,但我意识到它检测到我触摸了一个 sprite,即使它不是真的,似乎 sprite 是不可见的。当我触摸 Sprite 时,我将其移除,但它可能不会移除它。这是我的代码:

@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;
}
}
}

最佳答案

您没有从 spriteArray 中删除 Sprite 。因此,您还将检查已删除 Sprite 的触摸情况。尝试一下

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;
}
}

关于ios - 检测 CCSprite(包含在数组中)在屏幕上拖动手指的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23831607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com