- Home /
How many degrees must object turn in y-axis to face target?
Hi!
I have a player object and a target object. By clicking I can set the target object to any location in the scene. The player object turns then towards the target in y-Axis with Quaternion.LookRotation. I want the turning speed of the player to be in relation to how many degrees he has to turn in y-Axis when the target is stet to a new location. How can I get the amount of degrees in y-Axis the player will have to turn to a new set target? Thank you!
Answer by JinJin · Apr 23, 2015 at 10:12 AM
Use this function. It was written with assumption that the vectors are in the XZ plane (that is why it checks cross.y for the sign).
Vector3 one = playerObject.transform.forward;
Vector3 two = targetObject.transform.position - playerObject.transform.position;
/// <summary>
/// Angle between vectors from -179 to 180.
/// </summary>
/// <returns>From -179 to 180.</returns>
/// <param name="one">One.</param>
/// <param name="two">Two.</param>
public static float AngleBetweenVectors(Vector3 one, Vector3 two)
{
float a = one.sqrMagnitude;
float b = two.sqrMagnitude;
if (a > 0.0f && b > 0.0f)
{
float angle = Mathf.Acos(Vector3.Dot(one, two) / Mathf.Sqrt(a * b)) * 180.0f / Mathf.PI;
Vector3 cross = Vector3.Cross(one, two);
//float sign = Mathf.Min( Mathf.Min(cross.x, cross.y), cross.z );
float sign = cross.y;
if (sign < 0.0f)
return -angle;
else
return angle;
}
return 0.0f;
}
Your answer
Follow this Question
Related Questions
More specific Quaternion.LookRotation 1 Answer
Quaternion.LookRotation precision error 1 Answer
using Lerp and Quternion for turning does not work exactly in degrees!!!!? 2 Answers
Slerp to make the right/left side face another object 2 Answers
transform.right = (point on axis) after using LookAt? 2 Answers