- Home /
 
The question is answered, right answer was accepted
Lerping smoothly between animation and new position
Title is a bit confusing.
Basically I have a character with an idle animation, and when the player gets near the character, I want the character to turn its head towards the player smoothly.
The idle animation has head keyframes so I have no idea how to do this.
Answer by hameed-ullah-jan · Apr 14, 2019 at 02:56 PM
For such kind of work, look the Inverse Kinematics in unity, they work best in such senarios, but you have to give it time to learn
Answer by highpockets · Apr 14, 2019 at 03:20 PM
You can use Quaternion.Slerp and override any animation in LateUpdate(). On the frame you know you want to start this, call StartOverride(), but you will have to have a transition out of this as well, if you want the head to return to the original sate, but this should get you started:
 Quaternion lastHeadRot;
 public Transform target;
 public Transform head;
 
 public void StartOverride(){
 lastHeadRot = head.rotation;
 }
 
 void LateUpdate(){
 float angle = Vector3.Angle(head.forward, target.position - head.position);
  
   if (angle > 0.0f)
    {
 head.rotation = lastHeadRot;
 
  Vector3 targetDir = target.position - head.position; 
                 Vector3 currentDir = head.forward;
 if( -currentDir == targetDir ){
 head.Rotate(0,1,0);
 }
  Vector3 rotAxis = Vector3.Cross(currentDir, targetDir); //get rotation axis
                 float rotAngle = Mathf.Sqrt(Vector3.Dot(currentDir, currentDir) * Vector3.Dot(targetDir, targetDir)) + Vector3.Dot(currentDir, targetDir); //Get rotation angle
                 Quaternion newRot = new Quaternion(rotAxis.x, rotAxis.y, rotAxis.z, rotAngle).normalized;
                 timer = (1.0f - (angle / 181.0f)) * speed;
                 head.rotation = Quaternion.Slerp(head.rotation, newRot * head.rotation, timer);
 
 lastHeadRot = head.rotation;
 }
 }
 
               Code is not tested, but should work for you