0
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$
    – bummzack
    Jul 5 '12 at 22:11
  • \$\begingroup\$ @bummzack In the app the CCSprite is being moved by the accelerometer \$\endgroup\$
    – Coder404
    Jul 6 '12 at 0:34
3
\$\begingroup\$

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)
);
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .