# Question Keyframes for Quaternions???

Discussion in 'Animation' started by dips234, Jun 24, 2023.

1. ### dips234

Joined:
May 31, 2019
Posts:
9
Unity does not allow direct modifications of the quaternion for Transform.localRotation(). If I want to create simple animations for geometric gameobjects through script then I'm dead in the water.

<This should work>
AnimationClip.SetCurve(relativePath, typeof(Transform), "localPosition.x", new AnimationCurve(keyframes));
...
<This cannot work>
AnimationClip.SetCurve(relativePath, typeof(Transform), "localRotation.x", new AnimationCurve(keyframes));
...
<This should work>
AnimationClip.SetCurve(relativePath, typeof(Transform), "localScale.x", new AnimationCurve(keyframes));

Any suggestions for working around this?

2. ### halley

Joined:
Aug 26, 2013
Posts:
2,558
The individual elements of a quaternion are not independent. They all four must change in unison, according to a seemingly weird rule that the 4-dimensional length of the vector remains exactly 1.0. If the .x drops, another member like .w or .y must increase to make up the change. This is due to the mathematics of what makes up a quaternion, it's not something Unity can modify.

If you want to use animation curves to adjust an object's orientation, I suggest you have one Vector3 curve for the "forward" vector (the direction the +Z faces), and one Vector3 curve for the "up" vector (the direction the +Y faces), and then compute the quaternion using the
``Quaternion.LookRotation()``
function. This approach would work fine for localRotation or rotation purposes, but of course the animated vectors would have to be in the correct space. You can skip the +Y animation curve in many cases as long as the +Z vectors never approach the same direction, as the LookRotation is forgiving as long as there is at least a few degrees of separation between the two; it always favors the +Z and uses the +Y as a hint.

3. ### dips234

Joined:
May 31, 2019
Posts:
9
Key frames only work with a single float value, I can't keyframe the orientation of my gameobject's transform with the method you described, which is what I'm trying to achieve.

4. ### halley

Joined:
Aug 26, 2013
Posts:
2,558
Yes, but you can keyframe vectors for the "forward.x", "forward.y", "forward.z", "up.x", etc., which are all independent variables unlike quaternions. The use of these curves must then be combined via code using LookRotation.

5. ### dips234

Joined:
May 31, 2019
Posts:
9
I see what you mean. Interesting. Let me give it a go.