For humanoid characters, we can use the IK approach. To do so, follow these steps:
- Make sure to check the IK Pass option in the Animator Controller's layer properties.
- Create a new script and call it CharacterLookAtIK.cs.
- Create a void OnAnimatorIK(int layerIndex) function in that script. This function is called in the IK Pass after all animations are evaluated.
- In that script, we use the SetLookAtPosition() and SetLookAtWeight() functions on the Animator component. We use a public Transform target variable to set the look at position and a public float weight variable to set the weight of the look at. We also use the Vector3.SmoothDamp() method to damp any sudden changes in the position of our target:
targetPosition = Vector3.SmoothDamp(targetPosition, target.position, ref dampVelocity, dampTime); anim.SetLookAtPosition(targetPosition); anim.SetLookAtWeight(weight);
- Save the script and assign it to the character.
- Assign the Target game object to the Target field in the script's Inspector. Make sure to set the Weight field to 1.
- Play the game and move the Target game object to see the result (you can do it in the Scene View).
- To turn the look at on and off smoothly, interpolate the weight value in time using the Mathf.Lerp() function.