Vector to angle

Hi, I would like to know how to convert Vector to Angle.

For example:

x : y → Expected result


0 : 1 → 0

1 : 0 → 90

-1 : 0 → 270

0 : -1 → 180

1 : 1 → 45

-1 : 1 → 315

1 : -1 → 135

-1 : -1 → 225

Is there any way to count it?

Thanks.

Well, you have two unusual things (compared to plain Trigonometry). o° is normally right (1,0) and it usually goes counter clockwise, so 90° would be up (0,1).

To get the angle you usually use atan2 (in Unity Mathf.Atan2).

However if you swap x and y it should be what you want since swapping x<—>Y should mirror everything on the main diagonal.

Something like this should work:

    var angle = Mathf.Atan2(V.x, V.y) * Mathf.Rad2Deg;

Since it’s 2D, a little trig can do the magic:

function Angle(v: Vector3): float {
  // normalize the vector: this makes the x and y components numerically
  // equal to the sine and cosine of the angle:
  v.Normalize();
  // get the basic angle:
  var ang = Mathf.Asin(v.x) * Mathf.Rad2Deg;
  // fix the angle for 2nd and 3rd quadrants:
  if (v.y < 0){
    ang = 180 - ang;
  } 
  else // fix the angle for 4th quadrant:
  if (v.x < 0){
    ang = 360 + ang;
  }
  return ang;
}

For C#, just change the first line as below (the rest of the code is the same):

float Angle(Vector3 v){
  ...

Solved!

  	float angle = Vector3.Angle(new Vector3(0.0f, 1.0f, 0.0f), new Vector3(x, y, 0.0f));
		if (x < 0.0f) {
			angle = -angle;
			angle = angle + 360;
		}