I would like to calculate angle between two 2D vectors. Here's a picture of what I'm trying to achieve:
I have an obstacle line segment AB and incoming moving PC. If I'm coming from one side C¹D¹ and angle ⍺ < π/2 (i.e. right side) then PC will turn left. On the other hand if ⍺ > π/2 then PC will turn right. But if PC will come from the other side C²D² it should work as well for angle β as per picture.
So what I need is to determine whether the angle between AB and CD is larger to the left or right basically.
I've tried these things, while having vectors defined as:
Vector2 ab = Vector2.Normalize(new Vector2(b.x - a.x, b.y - a.y));
Vector2 cd = Vector2.Normalize(direction);
1) To calculate angle using atan2, but it works only randomly (1/4 of cases).
Single angle = Math.Atan2(cd.Y, cd.X) - Math.Atan2(ab.Y, ab.X);
if (angle > MathUtil.PiOverTwo)
{
RotateRight();
}
else if (angle < MathUtil.PiOverTwo)
{
RotateLeft();
}
2) To use normals somehow. This works a bit better but only from one side I think. (1/2 of cases, better but not there)
Vector2 normal1 = Vector2.Normalize(new Vector2(-ab.Y, ab.X));
Vector2 normal2 = Vector2.Normalize(new Vector2(ab.Y, -ab.X));
Double angle1 = Math.Atan2(normal1.Y, normal1.X) - Math.Atan2(cd.Y, cd.X);
Double angle2 = Math.Atan2(normal2.Y, normal2.X) - Math.Atan2(cd.Y, cd.X);
if (angle1 > angle2)
{
RotateRight();
}
else if (angle1 < angle2)
{
RotateLeft();
}