简体   繁体   中英

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?

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. CCActions can have callbacks that tell you when they're completed; see the header.

  • You can define an update: method and enable it with scheduleUpdates to be able to test the position every frame.

  • 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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