Search Unity

Question Using OnAnimatorIK to rotate the head when looking

Discussion in 'Scripting' started by matiasges, May 19, 2021.

  1. matiasges

    matiasges

    Joined:
    Jan 24, 2021
    Posts:
    142
    I'm making a first person perspective game view and I have all of the animations working; idle, walk, jump, crouch, etc but what I want to get now is to rotate the head when the camera's player is looking up or down. I've seen that the easiest way to achieve it (without creating more animations) is with the function OnAnimatorIK (). However I can't make my script to work inside it.
    Here is the code:
    Code (CSharp):
    1.  protected virtual void OnAnimatorIK(int layerIndex)
    2.         {
    3.             Vector3 dir = (target.position - headTransform.position); // world space target direction
    4.             dir = headTransform.InverseTransformDirection(dir); // to head local space target direction
    5.             Quaternion headRot = Quaternion.LookRotation(dir); // Get local quaternion
    6.  
    7.             anim.SetBoneLocalRotation(HumanBodyBones.Head, headRot); // apply to bone
    8.         }
    I also tried with this code with no success:

    Code (CSharp):
    1. protected virtual void OnAnimatorIK(int layerIndex)
    2.         {
    3.             Transform head = anim.GetBoneTransform(HumanBodyBones.Head);
    4.             Vector3 forward = (head.position).normalized;
    5.             Vector3 up = Vector3.Cross(forward, transform.right);
    6.             Quaternion rotation = Quaternion.Inverse(transform.rotation) * Quaternion.LookRotation(forward, up);
    7.             anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation);
    8.         }
    Any ideas?



    BTW I don't have any compile errors or warnings

    @Mecanim-Dev maybe you know?
     
    Last edited: May 19, 2021
  2. matiasges

    matiasges

    Joined:
    Jan 24, 2021
    Posts:
    142
    Well, I solved it using this simple code:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class LookAt : MonoBehaviour
    5. {
    6.     private Animator anim;
    7.     private Camera mainCamera;
    8.  
    9.     void Start()
    10.     {
    11.         anim = GetComponent<Animator>();
    12.         mainCamera = Camera.main;
    13.     }
    14.  
    15.     void OnAnimatorIK(int layerIndex)
    16.     {
    17.         anim.SetLookAtWeight(1f, 0f, 1f, .5f, .5f);
    18.         Ray lookAtRay = new Ray(transform.position, mainCamera.transform.forward);
    19.         anim.SetLookAtPosition(lookAtRay.GetPoint(25));
    20.     }
    21. }
    If someone is interested :)
     
    Kurt-Dekker likes this.