Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

In my cocos2d app I have a CCSprite moving on the screen but it moves off the screen. How can I prevent the CCSprite from moving off the screen?

Thanks

share|improve this question
    
You didn't provide enough information. CCSprites don't magically move off the screen. Are you using Actions? Do you change anything in your update method or do you use a physics-engine? –  bummzack Jul 5 '12 at 22:11
    
@bummzack In the app the CCSprite is being moved by the accelerometer –  Coder404 Jul 6 '12 at 0:34

1 Answer 1

up vote 3 down vote accepted

You have to make sure your sprite-rectangle is always within the screen bounds. You can ensure this by clamping the x, and y position of the sprite within the screen bounds.

Something like this (this is assuming the anchor point of the sprite is at its center, which is the default):

// move sprite using accelerometer

// get screen size
CGSize screen = [[CCDirector sharedDirector] winSize];

// get sprite size
CGSize size = sprite.contentSize;

// get sprite position
CGPoint pos = sprite.position;

// set new position constrained to screen bounds
sprite.position = ccp(
    clampf(pos.x, size.width * 0.5f, screen.width - size.width * 0.5f),
    clampf(pos.y, size.height * 0.5f, screen.height - size.height * 0.5f)
);
share|improve this answer
    
THANK YOU SO MUCH!!!!! –  Coder404 Jul 6 '12 at 20:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.