I have a piece of code that returns the angle between two vectors in the range of [0,360]. For this I used this question: Direct way of computing clockwise angle between 2 vectors. Now I need to create a function that takes a vector and an angle as input and returns a vector, that has the specified angle with the inputvector. The length of this vector doesn't matter. For this, I need to know how to reverse the effect of Atan2. The rest is pretty simple math.
internal virtual double AngleWith(Vector2 direction, Vector2 location)
{
Vector2 normDir = Vector2.Normalize(direction);
Vector2 normLoc = Vector2.Normalize(location);
double dot = (normDir.X * normLoc.X) + (normDir.Y * normLoc.Y);
double det = (normDir.X * normLoc.Y) - (normDir.Y * normLoc.X);
return Math.Atan2(-det, -dot) * (180 / Math.PI) + 180;
}
Any help is appreciated.
I don't know what you need this for, but arguably there is merit in transforming your vectors from the x,y-coordinate system to the polar coordinate system, in which points in a plane are given by their distance from the origin and the angle to a reference vector (for instance the x-axis in the explanation below), or
To convert from
(x, y)to(r, t)withrbeing the distance between(x,y)and(0,0)andtbeing the angle in radians between the x-axis and the line connecting(0, 0)and(x, y), you use this:The result can be stored in
Vector2, just like withxandy. You just have to remember that the values inside don't signifyxandy.If you want the difference in angle, you can just subtract
t2andt1of your polar coordinates (in radians, still need to convert to degrees).If you need to add a certain angle in degrees, just add or subtract it to the
tvalue of your polar coordinate.To convert back to
xandy, use