2
votes

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

}
2
CCSprite won't move unless you set its new position or you use CCMoveTo/By .. in both cases you have the control over where the sprite moves to so just put the logic restricting the y-coordinate there .. - Lukman
Take a look at my edit, I got that code but I am just not sure what to do in the if statements! - SimplyKiwi
for doing something like this for whole map check this : gamedev.stackexchange.com/questions/76067/… - Emadpres

2 Answers

4
votes

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));
2
votes
 CGSize winSize = [[CCDirector sharedDirector] winSize];
CCSprite* sprite = [CCSprite node];
CGSize spriteSize = sprite.boundingBox.size;
if ((sprite.position.y + spriteSize.height/2 < 0 )||(sprite.position.y + spriteSize.height/2 > winSize.height) ) {
    //Sprite is out of screen
}

not tested, but since you have the anchorpoint at 0.5, 0.5 as standard this should work for you