0
\$\begingroup\$

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);
}
\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ 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? \$\endgroup\$ – Coder404 May 12 '12 at 13:17
  • \$\begingroup\$ @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 \$\endgroup\$ – bummzack May 12 '12 at 13:39
  • \$\begingroup\$ 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))]; \$\endgroup\$ – Coder404 May 12 '12 at 14:13
  • \$\begingroup\$ @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 \$\endgroup\$ – bummzack May 12 '12 at 18:02
  • \$\begingroup\$ I wanted to make it so the "player" could not move off the screen when the device accelerates \$\endgroup\$ – Coder404 May 12 '12 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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