- Home /
How to make player look at opponents?
I want to make the player's head look at a nearby opponent if the opponent drives past the player. My confusion is how I would do this through an animation. I tried using lateUpdate and it mostly worked, but since blender uses a different rotational axis with z being up down, while in Unity, y is up and down, I get a really weird rotation of the player's head. How can I translate this into a proper rotation facing the opponent on only one axis? Thanks
Answer by UnityedWeStand · Jun 24, 2020 at 03:37 AM
I assume the weirdness is coming from the fact that you need to rotate the head in unity to get it "right side up" after exporting from blender. This causes the object to have a starting non-zero rotation, which makes any further changes to the rotation XYZ values non-intuitive.
The Easy Way
For all objects imported from blender, do not use them directly in Unity. Instead, set them as a child of an empty GameObject. You can rotate the child so that it is "right side up" in Unity, then perform all subsequent rotation stuff on the parent, which starts off with zeroed out rotation.
The Quaternion Way
Quaternions will help you immensely in this situation. First, with the object at zeroed out rotation, determine which of the object's transformation axes is the head's forward direction. Let's pretend that the imported head at zero rotation has the front directed upward along the Y-axis.
After rotating the imported object to be right side up, use Quaternion.FromToRotation() to create the "final state" rotation with the head looking at the target.
Quaternion finalRotation = Quaternion.FromToRotation(head.transform.up, new Vector3(target.transform.x - head.transform.x, 0, target.transform.z - head.transform.z))
The y component of the "To" Vector3 is set to zero to ensure rotation purely along the y-axis.
Finally, use Quaternion.Slerp() to animate the rotation via the time parameter. Note that you will need to store the initial rotation of the head for this method.
Quaternion initialRotation = head.transform.rotation;
void Update()
{
head.transform.rotation = Quaternion.Slerp(Quaternion.identity, finalRotation, time) * initialRotation;
time += Time.deltaTime;
}
Voila.
Your answer
Follow this Question
Related Questions
Look at like rotating around y axis 1 Answer
Get slerp to work just as LookAt(,Vector3.right) does 1 Answer
Have An Object Rotate Around Transform A So That Transform B is Looking at Transform C (C#) 0 Answers
how to limit axis of rotation when looking to a target 1 Answer
smooth look at with offset 0 Answers