简体   繁体   English

Cocos2D检查精灵是否在屏幕外?

[英]Cocos2D checking if sprite is off screen?

Im using this code to fire upwards: 我使用此代码向上触发:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent* )event
{

//Spawn the bullet
CCSprite * projectile = [CCSprite spriteWithFile:@"Projectile.png" rect:CGRectMake(0, 0,    17.5, 10)];
projectile.position = ccp(donk.position.x , 50);
[self addChild:projectile];

//Actualy Fire
[projectile runAction: [CCMoveTo actionWithDuration:.2 position: ccp (donk.position.x , 350)]];


}

It works like I want but how can i use an if statement to check if the projectile it is off the top off the screen so I can remove it? 它的工作方式就像我想要的一样,但是如何使用if语句检查射弹是否在屏幕的顶部,因此我可以将其删除?

I tried using this: 我尝试使用此:

    if (projectile.position.y >= 330) {
    CCLOG(@"Removed");
    [self removeChild:projectile cleanup:YES];
}

but I forgot that touches ended is only called once. 但我忘了触摸结束只被调用一次。

Think about when you should be checking whether the bullet is offscreen. 考虑何时应该检查项目符号是否在屏幕外。 Not at the same instant it was fired, right? 不是同时发射的,对吧?

There are many ways to do this. 有很多方法可以做到这一点。

  • You have a moveTo action already. 您已经有一个moveTo动作。 CCActions can have callbacks that tell you when they're completed; CCActions可以有回调函数来告诉您何时完成。 see the header. 参见标题。

  • You can define an update: method and enable it with scheduleUpdates to be able to test the position every frame. 您可以定义一个update:方法,并使用scheduleUpdates启用它,以便能够测试每帧的位置。

  • If you use a physics engine, you can make a "wall" for the edge of the screen and remove the bullet in response to collision detection. 如果您使用物理引擎,则可以在屏幕边缘制作“墙”,并根据碰撞检测将子弹移开。

There are probably other ways, too. 可能还有其他方法。 Look into what the framework provides. 查看框架提供的内容。

What about this: 那这个呢:

[projectile runAction:[CCSequence actions:
                       [CCMoveTo actionWithDuration:.2 position:ccp(donk.position.x,350)], 
                       [CCCallBlock actionWithBlock:^{
        [projectile removeFromParentAndCleanup:YES];
    }], 
                        nil]];

(not tested) (未测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM