Search code examples
ioscocos2d-iphoneccsprite

Cocos2D prevent sprite from going off-screen?


Is it possible to prevent my CCSprite from going off-screen? I already allow it to go offscreen on the left and right so that is fine but I just want to stop it from going off screen on the top and bottom.

So far what I have done is just cause the sprite to just get stuck on either the top or bottom. I don't want this to affect the movement of the sprite, all I want to happen is the CCSprite will just stop when it hits the top or bottom.

Can anyone show me how to do this?

Thanks!

Edit:

CGSize size = [[CCDirector sharedDirector] winSize];

if ((sprite.y <= size.height) && (sprite.y >= 0) ) {
    // Set new position

} else {
   // sprite is colliding with top/bottom limits, do whatever you like, for example change direction

}

Solution

  • To limit the sprite within a boundary, don't check the current position but check the new position instead. But, rather than using (possibly multiple) if conditions, you can use clamping method:

    Technique 1 - using MIN and MAX combo:

    CGPoint newPosition = ... (assign new position here using touch location or something)
    sprite.position = ccp(newPosition.x, MAX(0, MIN(size.height, newPosition.y)));
    

    Technique 2 - using clampf:

    CGPoint newPosition = ... (assign new position here using touch location or something)
    sprite.position = ccp(newPosition.x, clampf(newPosition.y, 0, size.height));