MAGS94
MAGS94

Reputation: 510

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?

Upvotes: 3

Views: 1141

Answers (2)

Madmenyo
Madmenyo

Reputation: 8584

Get the vector of both points and subtract there rotation/worldAngle. Something like this should do:

Vector2 v1 = point1.cpy().sub(origin);
Vector2 v2 = point2.cpy().sub(origin);
float angle1 = v1.angle();
float angle2 = v2.angle();

float angleBetween = Math.abs(angle1 - angle2));
//If the angle is more then 180 then comparing the other way around would be shorter.
if (angleBetween > 180)
    angleBetween = 360 - angleBetween;

Upvotes: 0

noone
noone

Reputation: 19776

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.

Upvotes: 3

Related Questions