Search code examples
libgdx

Angle between 2 points related to a center point in libgdx


I want to get the angle between point 1 and point 2 in relation to a center point. How do I do this using Vector2?

Vector2 center = new Vector2((float)Gdx.graphics.getWidth /2, (float)Gdx.graphics.getHeight /2);
Vector2 point1 = new Vector2(center.x, center.y + 200.0f);
Vector2 point2 = new Vector2(center.x + 200.0f, center.y);

It should be 90°, but how do I get that?


Solution

  • Vector2 center = new Vector2(500, 500);
    Vector2 point1 = new Vector2(center.x, center.y + 200.0f);
    Vector2 point2 = new Vector2(center.x + 200.0f, center.y);
    
    point1.sub(center).nor();
    point2.sub(center).nor();
    
    float angle = (MathUtils.atan2(point1.y, point1.x) - MathUtils.atan2(point2.y, point2.x));
    angle *= MathUtils.radiansToDegrees;
    System.out.println(angle); // 90.0
    

    The angle calculation can be looked up anywhere on the internet. For example here.

    It works with one additional step that we perform before the calculation. We need to treat the center as the (0, 0) origin, by subtracting it from the points and normalize them afterwards.