如何保证每个场景中只出现一个精灵?

每次触摸屏幕都会出现精灵,然后它会锁定在指定区域。要如何操作,我才能保证,即使多次触摸屏幕,每次在退出场景或碰到物体之前,场景中只出现一个精灵?
我现在采用的代码如下:

- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
// 1
CGPoint touchLocation = [touch locationInNode:self];

// 2
CGPoint offset    = ccpSub(touchLocation, _player.position);
float   ratio     = offset.y/offset.x;
int     targetX   = _player.contentSize.width/2 + self.contentSize.width;
int     targetY   = (targetX*ratio) + _player.position.y;
CGPoint targetPosition = ccp(targetX,targetY);

// 3
CCSprite *projectile = [CCSprite spriteWithImageNamed:@"projectile.png"];
projectile.position = _player.position;
projectile.physicsBody = [CCPhysicsBody bodyWithCircleOfRadius:projectile.contentSize.width/2.0f andCenter:projectile.anchorPointInPoints];
projectile.physicsBody.collisionGroup = @"playerGroup";
projectile.physicsBody.collisionType  = @"projectileCollision";
[_physicsWorld addChild:projectile];

// 4
CCActionMoveTo *actionMove   = [CCActionMoveTo actionWithDuration:1.5f position:targetPosition];
CCActionRemove *actionRemove = [CCActionRemove action];
[projectile runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove]]];

[[OALSimpleAudio sharedInstance] playEffect:@"pew-pew-lei.caf"];

}

原文:Only one sprite on the scene at once Cocos2D 3.x

阅读 2.8k
1 个回答

答:Joel Hernandez
以我的理解,你可以简单的添加一个flag,这样可以让精灵在场景中更容易辨识。只要在类别上添加:

BOOL isSpritePresent;

然后,在自定义ID的方法中将其初始化

-(id)init {
self=[super init];
isSpritePresent=NO;
return self; }

然后在TouchBegan的启动项中,添加:

if(isSpritePresent){
return; //As there's already an sprite on the scene.
}

在末尾项中添加:

isSpritePresent=YES;

最终,当箭头到达目标位置时,可以调用一种适应的方法重置Boolean。
如果你想要更加简便的实现预期效果,可以在其它动作效果之后添加如下的延迟方法:

CCActionDelay *delay = [CCActionDelay actionWithDuration:1.2f];
        [projectile runAction:[CCActionSequence actionWithArray:@[actionMove,actionRemove,delay]]];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题