我正在使用cocos2d来构建游戏。我有一系列CCSprites,我希望能够触摸它们并删除被触摸的那个。
现在我有这个......
-(void) spawn {
mySprite = [CCSprite spriteWithFile:@"image.png"];
mySprite.position = ccp(positionX,positionY);
[myArray addObject:mySprite];
[self addChild:mySprite];
}
- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
NSUInteger i, count = [myArray count];
for (i = 0; i < count; i++) {
mySprite = (CCSprite *)[myArray objectAtIndex:i];
if (CGRectContainsPoint([mySprite boundingBox], location)) {
[self removeChild:mySprite cleanup:YES];
}
}
我以前从未这样做过。有没有人有解决方案?
谢谢, 迈克尔
答案 0 :(得分:1)
- (void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch* touch = [touches anyObject];
CGPoint location = [touch locationInView: [touch view]];
NSMutableArray *spritesToDelete = [[NSMutableArray alloc] init];
for(CCSprite* mySprite in myArray) {
if (CGRectContainsPoint([mySprite boundingBox], location))
[spritesToDelete addObject:mySprite];
for(CCSprite* deadSprite in spritesToDelete) {
[self removeChild:deadSprite cleanup:YES];
[myArray removeObject:deadSprite];
}
}
此代码使用for-each创建符合条件的对象数组,然后将其删除。