- Home /
Rotation drift with transform.eulerAngles
I've been working on a simple script to try and set the Y rotation of an object based on the Y rotation of another gameobject. It kinda works but I see errors creep in at certain angles, particularly when oriented straight up.
using UnityEngine;
using System.Collections;
public class yRotationGrabber : MonoBehaviour {
public GameObject yTargetObject;
private float yRot;
void Start () {
}
void Update () {
yRot = yTargetObject.transform.eulerAngles.y;
transform.eulerAngles = new Vector3 (transform.rotation.eulerAngles.x, yRot,transform.rotation.eulerAngles.z);
}
}
I'm attaching it to an object that I want to draw Y rotation from an HMD (I don't know if this is part of the problem).
From the docs I see "Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; ) since this will lead to drift and undesired rotations. When setting them to a new value set them all at once as shown above. Unity will convert the angles to and from the rotation stored in Transform.rotation." hence why I tried to set all of the angles at once, but I still run into this drift issue. Is it due to grabbing only the Y rotation from the guide object (I would have thought that fact that it's re-assessing the Y direction every frame would mean that errors would quickly self correct)? If so, how do I fix this while still only rotating in the Y axis? I'm probably missing something simple here.