Small offset when calculating rotation based on touch point

android, java, libgdx, math

Solution

The position is in the lower left regardless of the origin, because origin is relative to position. So you are calculating the angle based on the lower left of the sprite instead of the center. You need to offset the position by the origin if you want to measure your angle relative to the center of the sprite.

double angle = Math.atan2(
    vector.y - position.y - spriteOrigin.y, 
    vector.x - position.x - spriteOrigin.x);

Also keep this in mind when drawing your sprite...it's position is always in the lower left, so take that into account when setting its position.

Problem

I need to have a sprite face the cursor/touch point. The vector of the touch point is calculated as follows: ``` game.getCamera().unproject( new Vector3().set(Gdx.input.getX(), Gdx.input.getY(), 0) , 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) ``` And then I calculate the degrees the sprite needs to turn with the following method: ``` public void rotateTo(Vector3 vector) { double angle = Math.atan2(vector.y - position.y, vector.x - position.x); rotation = (float) Math.toDegrees(angle) - 90; sprite.setRotation(rotation); } ``` The problem is that there is a small offset in some rotations for example(The red dot indicates the touch position and the arrow is the sprite that needs to be rotated), in the first picture its roughly where it should be but in the others its way off, what could be causing this bug?: As you can see in the first 2 pictures with a small change in the X axis the accuracy decreases dramatically. More examples:

Original source