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?
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) );