开发者

Android - problem with Math.atan2

So in my android game I'm making with andengine, I have it set up so as I touch and drag the player sprite, it continously rotates so that the character is always facing the direction it is traveling.

public class Player extends AnimatedSprite {
private float lastX = Game.centerX;
private 开发者_开发问答float lastY = Game.centerY;
private static int angle = 0;

// ...

@Override
public boolean onAreaTouched(final TouchEvent sceneTouchEvent, final float touchAreaLocalX, final float touchAreaLocalY) {
    Body body = OrbCatch.physicsWorld.getPhysicsConnectorManager().findBodyByShape(this);
    if (sceneTouchEvent.getAction() == TouchEvent.ACTION_MOVE) {
        float currentX = sceneTouchEvent.getX();
        float currentY = sceneTouchEvent.getY();
        angle = (int) (Math.atan2(currentY - lastY, currentX - lastX) * 180 / Math.PI);
        lastX = currentX;
        lastY = currentY;
    }
    body.setTransform(new Vector2(sceneTouchEvent.getX(),sceneTouchEvent.getY() )
    .mul(1/PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT),angle);
    return true;
}

}

The key line is this:

angle = (int) (Math.atan2(currentY - lastY, currentX - lastX) * 180 / Math.PI)

It takes the last known coordinates and the current coordinates, calculates the angle between them, and converts it from radians to degrees. Well, this was all working fine yesterday, but despite changing none of this code today it's behaving strangely. The sprite's orientation changes erratically, with no apparent pattern. If I move it in a straight path, it continuously alternates between 2 or 3 distinctly different angles(usually one of them is the correct one).

edit: solved, see below


The problem was that Body.setTransform angle parameter takes values in radians, not degrees. Andengine is so poorly documented...


math.todegree(math.atan(....))....

You should use toDegree().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜