How to get angle between 2 Vector2D's C++

As the title suggests i am trying to find the angle between 2 Vector2D points. such as 200,300 and 400,300.

Updating my answer. My first solution needs normalized vectors.

FQuat Between = FQuat::FindBetween(FVector(Your2DVector1, 0.0f).Normalize(), FVector(Your2DVector2, 0.0f).Normalize());
FRotator MyRot(Between);
float Angle = FMath::Abs(MyRot.Yaw);

To make it more compact:

float Angle = FMath::Abs(FQuat::FindBetween(FVector(Your2DVector1, 0.0f).Normalize(), FVector(Your2DVector2, 0.0f).Normalize()).Rotator().Yaw);
  • Note that this method doesn’t return a reliable direction of rotation (clockwise or counter-clockwise, positive or negative), so the ‘Abs’ is needed. You need a second test to determine direction (a dot with the right vector is easiest).

You can also do the exhaustive mathematical approach:

float Angle = FMath::RadiansToDegrees(FMath::Acos(FVector2D::DotProduct(Your2DVector1.Normalize(), Your2DVector2.Normalize())));
  • Note this will return a positive value regardless of which direction of rotation is needed. Also needs a secondary operation to determine direction.

Finally:

float Ang1 = FMath::Atan2(Your2DVector1.X, Your2DVector1.Y);
float Ang2 = FMath::Atan2(Your2DVector2.X, Your2DVector2.Y);
float Ang = FMath::RadiansToDegrees(Ang1 - Ang2);
if(Ang > 180.0f) Ang -= 360.0f; else if(Ang < -180.0f) Ang += 360.0f;
  • Note, although ‘clunky’, this method returns not only the correct angle, but also the correct direction of rotation (for Your2DVector1 to rotate to Your2DVector2. Reverse the order of subtraction (third line) if you want it the other way). Only works in 2D though (or 3D if the Z axis doesn’t matter).

But as far as I know, there no singular library function that does it. I think someone should add it to FVector and FVector2D.

2 Likes