Calculating an angle from a Vector2

February 28, 2009 .net vectors xna

When you need to calculate an angle from a Vector2 structure, you can use this piece of code:

public static class Vector2Helper
{
	public static float CalculateAngle(Vector2 v)
	{
		float angle = 0.0f;

		if(v != Vector2.Zero)
		{
			v.Normalize();

			angle = (float)Math.Acos(v.Y);

			if(v.X < 0.0f)
			angle = -angle;
		}

		return angle;
	}
}

I used this to calculate an angle from the Vector2 of the Left Stick.

The original credit for this source code comes from here.