- Home /
Strange angle computing from car tutorial
Get the car tutorial from Unity tutorial, and when read the C# source in file CarController.cs, I find this line of code:
float angle = -Mathf.Asin(Mathf.Clamp( Vector3.Cross(veloDir, carDir).y, -1, 1));
I don't understand what's angle is, and if you can explain, please also comment why only use y axis. thanks.
Answer by aldonaletto · Apr 25, 2012 at 12:31 PM
This is a smart way to get the angle between two horizontal vectors - Vector3.Angle is easier but only returns the absolute value, thus you can't say if it's to the right or to the left.
The cross product A x B returns a vector perpendicular to A and B, and with magnitude proportional to the sine of the angle between them. If A and B are unit vectors (with length = 1), the length of the vector returned is Abs(Sin(angle)).
In the case above, carDir and veloDir are probably horizontal vectors, thus the resulting cross product will be a vertical vector - and its Y value is numerically equal to the sine of the angle between them.
For more information about cross product, read the Mother of All Knowledge (aka Wikipedia): http://en.wikipedia.org/wiki/Cross_product
Aldo,
Very clear. One more question after your comment, if these 2 vectors aren't horizontal, is this algorithm reasonable? If it is, what is the result? Thanks.
I think (not 100% sure) that the cross.Y value is the sine of the angle measured between the two vectors in the plane perpendicular to Y. If the two vectors form a plane inclined relative to the world axes, I believe the values returned in X, Y and Z are the sines of the angles projected in their respective perpendicular planes - X is relative to the angle projected in YZ, Y relative to XZ, Z relative to XY.
Ok from what I know: you could think the 2 vectors form a triangle (if you join the end of each), then you have a plane. The vector from the cross product will always be perpendicular to that plane. Whatever orientation of the 2 original vectors. I guess that is pretty much what @AldoNaletto was saying.
Yes, like the image I borrowed from the wikipedia shows:
.
a and b are the two vectors, theta is the angle and n is the cross product. When a and b are unit vectors, the XYZ components of n are the sines of the angles projected on the corresponding perpendicular planes. If a and b form a horizontal plane (parallel to XZ plane), then n.Y is the sine of theta.
Your answer
Follow this Question
Related Questions
car tutorial problem 0 Answers
How to put Car Tutorial in Assets 1 Answer
Wheels can't touch the ground 1 Answer
Having trouble importing. 0 Answers
about the car tutorial sound problem 0 Answers