Hi, can someone please shed some light on Vector3.Angle for me?
I have two cubes in my scene, one at origin and the other at x5,y0,z5. Vector3.Angle returns 90 degrees as the angle between the cubes but unless I am not understanding it correctly the angle really looks like 45 degrees to me.
Scripting documentation doesn’t really help.
OK, so working back to school days (I was rubbish at trig) I found out how to make it work. You can get the relative positions of the two objects by subtracting the X and Y positions to give the Opposite and Adjecent lines of the triangle and then divide the opposite by the adjacent to give the Tangent and then you can calculate the radians by:
and then convert that to degrees by multiplying by:
So to convert the tangent into degrees to get the angle of one object to another you simply need to:
Most of the Unity things that look like math, really are standard, non-game math. You should be able to look up “3d angle” and get some nice pictures and an explanation.
Roughly, angle expects two “direction” vectors. It brings them start-to-start and measures. In other words, it pretends they are both coming out of 000. Then measures the protractor angle between them, like in regular trig. It’s really meant for people who know regular 3D math already, and want to use the same formulas in Unity.
Suppose you give it (1,0,-1) and (1,0,1). You might think that, since the second one is in front of the first, the angle is 0. The real rules line them up like
< and measure that angle (90, I think.)
If you really want the angle from one object to another, you can look up how to get that.
The way you described your problem is that you want the angle between the positive X axis and the vector between your two cubes.
If you want to get the angle between the two cubes and the vector (1, 0, 0) (positive X axis), do the following:
- Get the vector from cube 1 to cube 2. (I.e.
cube2_position - cube1_position)
Normalize that vector.
Dot the normalized vector with the vector (1, 0, 0).
- Take the arc-cosine of the result of the dot product.
This uses the fact that the dot product between two unit vectors is equal to the cosine of the angle between the two vectors. See the wikipedia page for more information.
My guess is that
Vector3.Angle(cube2_position - cube1_position, Vector3.right) does the same thing. (You have to give it two vectors that it can take the angle between. If one of those vectors is length 0, then you can’t really take the angle between it and some other vector.)