Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angle between 2 points related to a center point in libgdx

Tags:

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?

like image 437
MAGS94 Avatar asked Dec 09 '25 09:12

MAGS94


1 Answers

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.

like image 141
noone Avatar answered Dec 12 '25 07:12

noone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!