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

Im trying to, in cocos2d for the iPhone, move a CCSprite (in this case "player" up and down (the app is in landscape). How can I accomplish this? I have been unable to do so. ex.

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    player.position.x = acceleration.x * 10;
    NSLog(@"Accelerometer x value is %f\n", acceleration.x);
share|improve this question
up vote 1 down vote accepted

You can't change position components like x and y directly. You have to set a new position instead, by assigning a CGPoint to the position property. Something like this:

[player setPosition:ccp( acceleration.x * 10, player.position.y )];

If you want to move the sprite constantly in the direcion of acceleration, you should increment the x value instead.. something like this:

[player setPosition:
    ccp( player.position.x + acceleration.x * 10, player.position.y )];

Technical background: You have to use setPosition or position = ccp(xValue, yValue), because Cocos2D keeps a flag internally that indicates if the position has changed and if the sprite should be moved. Setting components like x or y directly won't do anything, because the flag only changes when you invoke the position setter.

share|improve this answer
Hey thank you so much for answering and for giving a fantastic answer! I plan on using the 2nd one. Just one sub question: How do I prevent the CCSprite from moving off the screen? – Coder404 May 12 '12 at 13:17
@Coder404 just clamp the x position to the desired bounds.. something like: MAX(0.0f, MIN(screenWidth, player.position.x)) or simply use ccClamp to get a point within screen bounds – bummzack May 12 '12 at 13:39
how could I implement MAX(0.0f, MIN(screenWidth, player.position.x)) into the code? like this? [player.position MAX(0.0f, MIN(screenWidth, player.position.x))]; – Coder404 May 12 '12 at 14:13
@Coder404 No, use [player setPosition: ccp(MAX(0.0f, MIN(screenWidth, player.position.x)), player.position.y)]... and ofc you'll have to replace screenWidth with the actual screen-width – bummzack May 12 '12 at 18:02
I wanted to make it so the "player" could not move off the screen when the device accelerates – Coder404 May 12 '12 at 18:49

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.