Does unity implement a way to convert an angle+magnitude representation of a vector to an x,y vector?

Hi all,

I need to create a two dimensional vector (z is 0) out of an angle and a magnitude. I can do this myself using trigonometric functions but it would be better if Unity already had something I could use.

Any ideas?

Thanks in advance.

R3po

There are lots of ways to achieve this, but it would be at least two-three+ function calls because you would need to:

  • convert the angle into a direction
  • multiply by the magnitude

But the order doesn't really matter, and then you'd have to convert to a vector2 if you need it that way.

The real problem in writing a function like that is that there is no way to know what the angle is relative to and so you must assume:

//Gets an XY direction of magnitude from a degree angle relative to the x axis
//Rotates a vector of magnitude along the x axis by degrees about the z axis
function GetXYDirection(angle : float, magnitude : float) : Vector2 {
    var rotation : Quaternion = Quaternion.AngleAxis(angle,Vector3.forward);
    var XYZdirection : Vector3 = rotation * Vector3(magnitude,0.0f,0.0f);
    return Vector2(XYZdirection);
}

But implementing your own with trigonometric functions is potentially more run-time efficient, depending on how you write it because either way it will involve at least one cosine and one sine, but doing it yourself in 2D would save you 1 whole dimension of multiplication.

//Gets an XY direction of magnitude from a radian angle relative to the x axis
//Simple version
function GetXYDirection(angle : float, magnitude : float) : Vector2 {
    return = Vector2(Mathf.Cos(angle), Mathf.Sin(angle)) * magnitude;
}