Search Unity

Allowing MouseLook during Mecanim Animation

Discussion in 'Animation' started by Cygon4, Mar 22, 2017.

  1. Cygon4

    Cygon4

    Joined:
    Sep 17, 2012
    Posts:
    382
    I want to allow the player character to look around while still playing animations on the same character.
    • I can get it to work (sort of) by posing my character's head bone in LateUpdate() (w/ update mode set to normal). However, this causes the head occasionally jerk in an unwanted direction.
    • I tried doing it via a "Body Mask" in which I excluded the head and neck bones from the animator controller's base layer, but the animator controller *still* gets applied to the head and neck bones. Is this a bug or can I not use masks on the base layer?
     
  2. Fabian-Haquin

    Fabian-Haquin

    Joined:
    Dec 3, 2012
    Posts:
    231
    The purpose of Body Mask is to play more than one animation on a single skinmesh, not to override a bone position/rotation in script.

    What you need is Animator.SetIKRotation or Animator.SetBoneLocalRotation.

    For the head you need SetBoneLocalRotation.

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class IkConstraint : MonoBehaviour
    5. {
    6.     private Animator animator;
    7.     private Transform headTransform;
    8.     public Transform target;
    9.  
    10.     void Start()
    11.     {
    12.         animator = GetComponent<Animator>();
    13.         headTransform= animator.GetBoneTransform(HumanBodyBones.Head);
    14.     }
    15.  
    16.     void OnAnimatorIK(int layerIndex)
    17.     {
    18.         Vector3 dir = (target.position - headTransform.position); // world space target direction
    19.         dir = headTransform.InverseTransformDirection(dir); // to head local space target direction
    20.         Quaternion headRot = Quaternion.LookRotation(dir); // Get local quaternion
    21.  
    22.         animator.SetBoneLocalRotation(HumanBodyBones.Head, headRot); // apply to bone
    23.     }
    24. }
     
    Last edited: Mar 22, 2017
    theANMATOR2b likes this.