Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to rotate a child object with animation

Discussion in 'Scripting' started by Baalhug, Jul 23, 2019.

  1. Baalhug

    Baalhug

    Joined:
    Aug 12, 2013
    Posts:
    32
    Hi, guys:

    I've been hours trying to accomplish something easy (or it looked like). I have a character model with an animation imorted into unity. It works good. Now I want the head looks in the direction of a target, even if the model is being animated. The animations make the character turns left or right by 60 degrees. So I wrote this code:
    Code (CSharp):
    1. using UnityEngine;
    2. public class CharBehaviour : MonoBehaviour
    3. {
    4.      public Transform head;
    5.      public Transform torax;
    6.      public Transform target;
    7.      private Animator anim;
    8.      private void Start()
    9.      {
    10.          anim = GetComponent<Animator>();
    11.      }
    12.      void LateUpdate()
    13.      {
    14.          Quaternion lookRotation = Quaternion.LookRotation(target.position - head.position);
    15.          if (lookRotation.eulerAngles.y > 60)
    16.          {
    17.              anim.Play("Turn_right");
    18.          }
    19.          if (lookRotation.eulerAngles.y < -60)
    20.          {
    21.              anim.Play("Turn_left");
    22.          }
    23.          head.rotation = lookRotation * head.rotation;
    24.      }
    25. }
    It works nice without the animation, the head indeed follows the target. But when I play the animation (lines 15-22), the object torax (grandparent of head) gets rotated by 60 degrees and the head is turned 60 degrees from the target direction (which is expected). I tried a lot of combinations after last line but none works. The head gets rotated in odd ways. If I do:

    Code (CSharp):
    1. head.rotation = torax.rotation * head.rotation;
    It does not work. Using localRotation no matter where it doesn't work either. I'm aware I don't understand Quaternions intuitivelly, but afaik combining rotations is done by multipliying them. What am I missing? Any ideas?
     
  2. Baalhug

    Baalhug

    Joined:
    Aug 12, 2013
    Posts:
    32
    Ok, I found the problem and the solution. The problem was character bones were imported into unity in different axis. Model was ok, but bones were not.
    So the solution is: In the FBX export menu in Blender there is a pair of options: (Primary and Secondary Bone Axis). I set them up to Primary = Z axis and Secondary = X axis. That solved the problem of bones. Then I just changed the lookRotation stuff for head.lookAt(target).
    Now it works perfect.