iphoneobjective-cipadcocos2d-iphoneaccelerometer

iPhone - Tilt to Move


In my iPhone game (I am using cocos2d, shouldn't make a massive difference) I want to have it like so:

You use the accelerometer to the move the sprite/player on the screen, with acceleration as you tilt more and also I want to have the sprite rotate to point in the direction you are tilting.


Solution

  • You can use a physics engine (I prefer Chipmunk, since it has a simpler API) to apply inertia and acceleration to a two-body system. Attach a fixed-length link between the bodies, and apply drag to both bodies, but give one body more drag than the other. Attach the sprite to the mid-point of these two bodies, and its angle matching the angle between the bodies, with the "front" of the sprite pointing towards the body with less drag.

    Unless you are already using a physics engine, this is more effort than a fudge-the-angles hack, but will look much more natural to the eye.

    EDIT: On a more recent project, I worked out a single-body technique using a groove joint (not sure what the Box2D equiv is) on the body with the anchor on the world. Locate the world's anchor away from the body's center of gravity and, on each step, move the anchor so that it remains in exactly the same body-relative position. The further away from the center of gravity you position the anchor, the more slowly the body will turn to face the direction of travel.