我正在使用 cocos2d 开发我的第一个游戏,但我遇到了一个我似乎无法找到正确解决方案的问题。我每秒从屏幕顶部到底部添加一个 CCSprite 并为其设置动画,当玩家触摸其中任何一个时,我需要隐藏这些精灵。所以我想给我添加的每个精灵都加上标签,然后用那个特定的标签访问那个精灵。我是否需要将标签号放入某个数组中,因为它们每秒都会增加,甚至在我以触摸方法访问它们之前?
- (void)addStraightBugs
{
currentAntTag++;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"smallAunt.plist"];
spriteSheetmedAnt = [CCSpriteBatchNode batchNodeWithFile:@"smallAunt.png"];
[self addChild:spriteSheetmedAnt z:0 tag:kSpriteManager];
CCSprite *ant= [CCSprite spriteWithSpriteFrameName:@"small-aunt1.png"];
[spriteSheetmedAnt addChild:ant z:1 tag:currentAntTag];
NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 2; ++i) {
[walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"small-ant%d.png", i]]];
}
CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.15f];
CCAction *action=[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
ant.position = ccp(100,500);
[ant runAction:action];
CGPoint realDest = ccp(60,140);
int minDuration = 2.0;
int maxDuration = 5.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;
[ant runAction:[CCSequence actions:
[CCMoveTo actionWithDuration:actualDuration position:realDest],
[CCCallFuncN actionWithTarget:self selector:@selector(moveFinished:)],
nil]];
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];
CCSpriteBatchNode *spriteManager;
spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
CCSprite *ant = (CCSprite*)[spriteManager getChildByTag:currentAntTag];
CGRect abc= CGRectInset([ant boundingBox],30, 85);
if(CGRectContainsPoint(abc,touchLocation))
{
ant.visible=NO;
}
}
我也有 3 个方法,每隔几秒调用一次,我创建这些 CCSpriteFrameCache 和 CCSpriteBatchNode 对象以使我的角色在动画时运行。像这样每秒创建缓存会不会太重,或者我应该在 init 方法中创建它们,然后在这里对 CCSprite 运行操作?