I was recently working on an XNA project and needed to convert from an angle to a Vector2. There are a lot of resources showing how to go one way (angle->Vector2) or the other (Vector2->angle) but not many showing both. So, I figured it might be helpful to put it up here, even if I only use it for reference.
Angle -> Vector2
1 2 3 4 |
float myAngleInRadians = Math.PI; Vector2 angleVector = new Vector2( (float)Math.Cos(myAngleInRadians), -(float)Math.Sin(myAngleInRadians)); |
Now, the reason I make the Y value negative is because that’s how the screen coordinate system works. If you didn’t do this, the angle in radians would go clock-wise instead of counter-clockwise.
Vector2 -> Angle
1 2 3 |
Vector2 angleVector = new Vector2(0, 1); float angleFromVector = (float)Math.Atan2(angleVector.X, -angleVector.Y); |
Here, we invert the Y value again to convert back to the angle.
Bastian says:
Thanks, this was of great help. I modified the code for getting/setting the radians in the range 0 to PI and used this in my Python 2D vector class like that:
def getRadians(self):
r = math.atan2(self.x, -self.y)
if r < 0.0:
return math.pi * 0.5 + (math.pi – -r) * 0.5
return r * 0.5
def setRadians(self, rad):
self.x = math.sin(rad * 2.0)
self.y = -math.cos(rad * 2.0)
Regards,
Bastian