您的源代码较少。但是,您可以使用将在接口中声明的整数变量。在实现中将整数变量设置为 0(在 init 方法中),当您创建新的错误时,将整数值再增加一并将错误精灵标签设置为整数值,如下所示:
// Interface
@interface yourScene:CCLayer {
int bugsCount; // add new variable for counting current bugs
}
// implementation
@implementation
-(id) init {
if( (self=[super init])) {
// Your code in init
// integer value for counting current bugs
bugsCount = 0;
}
return self;
}
-(void) addNewBug {
// your code of adding bugs
CCSprite *bug = [CCSprite spriteWithFile:@"bug.png"];
bugsCount++;
bug.tag = bugsCount; // Your bug sprite tag should be equal current bugsCount value
bug.position = ccp(x,y);
[self addChild:bug];
}
在 ccTouchEnded 方法中,只需执行 for 循环来检测选择了哪些错误,如下所示:
-(void) ccTouchesEnded:(NSSet*)touches withEvent:(id)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
location = [self convertToNodeSpace:location];
// Detecting bug by touch
for (i=1; i <= bugsCount; i++) {
// get bug sprite by tag (from bugsCount idea)
CCNode *bug = [self getChuldByTag:i];
if (CGRectContainsPoint(bug.boundingBox, location)) {
// add new score (now this will work)
score += 1;
NSLog(@"%i", score);
// remove bug from scene
[self removeChildByTag:1 cleanup:YES];
// decrease number of bugs
bugsCount--;
}
}
}