Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?


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


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.