- Home /
To rotate a head following a target
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:
using UnityEngine;
public class CharBehaviour : MonoBehaviour
{
public Transform head;
public Transform torax;
public Transform target;
private Animator anim;
private void Start()
{
anim = GetComponent<Animator>();
}
void LateUpdate()
{
Quaternion lookRotation = Quaternion.LookRotation(target.position - head.position);
if (lookRotation.eulerAngles.y > 60)
{
anim.Play("Turn_right");
}
if (lookRotation.eulerAngles.y < -60)
{
anim.Play("Turn_left");
}
head.rotation = lookRotation * head.rotation;
}
}
It works nice without the animation, the head indeed follows the target. But when I play the animation (lines 19-26), 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:
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?
Answer by Baalhug · Jul 23, 2019 at 02:38 PM
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.
Answer by JonPQ · Jul 22, 2019 at 10:50 PM
point the head using code, not animation. can't you do head.rotation = lookRotation to make the head look at the target ? If this works, add in a blended lerp, so the head has some acceleration and deceleration.
The head is already rotated using code, but the animation moves the whole character, so it rotates the head too.