Java – Calculate small offsets when rotating based on touch points

Calculate small offsets when rotating based on touch points… here is a solution to the problem.

Calculate small offsets when rotating based on touch points

I need to have the sprite face the cursor/touch point.
The vector for 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())

Then I calculate the number of degrees the sprite needs to turn using 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 (red dots indicate touch position, arrows are sprites that need to be rotated), in the first picture it is roughly where it should be but in others have gone, what caused this error? :

enter image description here
enter image description here

As you can see in the first 2 pictures, the X-axis has changed slightly and the accuracy drops dramatically.

More examples:

enter image description here
enter image description here

Solution

Regardless of the origin, the position is

in the lower left because the origin is relative to the position. So you calculate the angle based on the bottom left corner of the sprite instead of the center. If you want to measure the angle relative to the center of the sprite, you need to offset the position from the origin.

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

Keep

this in mind when drawing sprites as well… Its position is always in the bottom left corner, so take this into account when setting its position.

Related Problems and Solutions