# Angle between two vectors

How can I obtain the angle between two vectors, for example I have the following:

I know that the angle (in degrees) between A and B1 is 0, but how can I know the angle between A and B2, considering the axis orientation of the gameobject…

Any suggestions?

You can get the angle between two vectors using Vector3.Angle(v3A, v3B)

@DarkMatter’s answer is the solution for fast and easy solution with no possibility of error.

Now here the mathematics solution that lies under the Angle function in case you would need to stop on the way for any reason OR you want to make it hard on you:

``````var vec1=Vector3(2,3,4);
var vec2= Vector3(1,-2,3);
//Get the dot product
var dot:float = Vector3.Dot(vec1,vec2);
// Divide the dot by the product of the magnitudes of the vectors
dot = dot/(vec1.magnitude*vec2.magnitude);
//Get the arc cosin of the angle, you now have your angle in radians
var acos = Mathf.Acos(dot);
//Multiply by 180/Mathf.PI to convert to degrees
var angle = acos*180/Mathf.PI;
//Congrats, you made it really hard on yourself.
print(angle);
``````

Ran into trouble with the Vector3.Angle function, it was returning incorrect values. Found out there is a problem with this function when the vectors are too small, as seen in this question and answer. So I wrote my own angle functions that use Mathf.Atan2:

``````//This returns the angle in radians
public static float AngleInRad(Vector3 vec1, Vector3 vec2) {
return Mathf.Atan2(vec2.y - vec1.y, vec2.x - vec1.x);
}

//This returns the angle in degrees
public static float AngleInDeg(Vector3 vec1, Vector3 vec2) {
return AngleInRad(vec1, vec2) * 180 / Mathf.PI;
}
``````

See Atan2 for more details.

Since you are using two dimensional grid axis, I use Vector2. using Vector3 is nothing different than the one I wrote;

``````void Update(){
Vector2 PointA = new Vector2(z, y);
Vector2 PointB = new Vector2(z, y);
float Angle = Vector2.Angle(PointA, PointB);  //If the angle isn't correctly at 0, you can subtract this value by the offset degree
Debug.Log("Angle of PointA to PointB is " + Angle);
}
``````

This is done via C#.