I’m trying to find the angle between two gameObjects using vector3.angle…
var seekerObject : GameObject;
var targetObject : GameObject;
function Update () {
var seeker = seekerObject.transform;
var target = targetObject.transform;
var targetDir = (target.position - seeker.position);
var forward = seeker.forward;
var angleBetween = Vector3.Angle (targetDir, forward);
}
… and I’m having two problems:
-
The target object is a prefab that is instantiated when the scene starts. Although the origins for all objects in the prefab are at 0,0,0 I get incorrect angle results from this code.
-
This code results in Vector3.angle which gives me the angle in all 3 axis. For my purposes all I need is the angle around the world’s vertical axis, but I can’t seem to figure out how to do this?
For #2, simply flatten your vectors - set targetDir.y and forward.y to 0.
Thanks, that worked nicely. I also sorted out item #1.
Next issue: Vector3 just shows the angle but not the “direction”, ie. it shows that the angle is 30 degrees, but not whether it’s 30 degrees to the left or right. Is there an easy way to determine the direction from Vector3?
You can use Mathf.Atan2(vec.x, vec.z) to get the angle of a vector. Subtract the Atan2 of one from the Atan2 of the other, and voila.
I think the easiest way to get all the angles would be something like:
var targetVector = targetPoint - transform.position;
var seeker = transform.eulerAngles;
seeker.x = ClampAngle(seeker.x);
seeker.y = ClampAngle(seeker.y);
seeker.z = ClampAngle(seeker.z);
var target = Quaternion.LookRotation(targetVector).eulerAngles;;
var anglesBetween = target - seeker;
anglesBetween.x = ShortestAngle(anglesBetween.x);
anglesBetween.y = ShortestAngle(anglesBetween.y);
anglesBetween.z = ShortestAngle(anglesBetween.z);
//============================================
//============================================
function ClampAngle (angle : float) : float
{
if (angle < -360.0)
angle = angle + 360.0;
if (angle > 360.0)
angle = angle - 360.0;
return angle;
}
//=============================================
//============================================
function ShortestAngle (angle : float) : float
{
if (angle < -180.0)
angle = angle + 360.0;
if (angle > 180.0)
angle = angle - 360.0;
return angle;
}
Also, the left/right thing can be solved neatly using the cross product of the two vectors (see this thread for some code and see issue one of UDM for an article that explains how it works).