ios - 如何保证每个场景中只出现一个精灵?
迷茫
迷茫 2017-04-17 12:04:17
[iOS讨论组]

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

- (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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(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]]];
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号