transform.localrotation

Hi there

Just a quick question regarding local rotation function. I have a rotation and I would like to create another rotation relative to its parent rotation. For example, I would like the rotation speed to be half of its parent. Would this be possible with the transform.localrotation function.

Thanks in advance.

Regards

Yes it’s possible, however your question is a bit ambiguous.

Specifically “A Rotation” could mean either:

  • A rotation value (a quaternion) representing the rotation from one orientation to another.
  • An animation which rotates an object over time (by applying a small rotation each frame)

Also you haven’t said whether you’re using scripting or animation, but since you mentioned “Function” I’m guessing scripting.

This isn’t as easy as it might first appear, because if you have a series of objects parented to each other, and each examines its parent’s rotation, it will get a “Quaternion” value, which doesn’t tell you how many turns around its axis it has completed. Theres no easy way to get this information without storing it in a script yoruself, so that’s what I’ve done here. Hopefully it’s something along the lines of what you’re after:

The script should be placed on the root object and all child object. The root object treats the “amount” variable as a Euler rotation in x,y,z. Every child script treats it’s “amount” variable as the amount to multiply its parent’s rotaton by.

To see the effect, you therefore need to animate or script changes to this “amount” variable on the root object to rotate it, and the value will be passed down through all children that also have the script.

using UnityEngine;
using System.Collections;

public class RecursiveRotator : MonoBehaviour {

	public Vector3 amount;
	public Vector3 useAmount { get; private set; }
	Quaternion originalLocalRotation;
	RecursiveRotator parentRotator;

	void Start() {
		originalLocalRotation = transform.localRotation;
		if (transform.parent != null) 
		{
			parentRotator = transform.parent.GetComponent<RecursiveRotator>();
		}
	}

	void Update () {
		useAmount = amount;
		if (parentRotator)
		{
			useAmount = Vector3.Scale(parentRotator.useAmount, amount);
		}
		transform.localRotation = originalLocalRotation * Quaternion.Euler(useAmount);
	}
}

Here’s an example of a tree of recursive objects rotating based on their parent. I have all the child objects set to an amount of 1.5, 1.5, 1.5. Then I manually animate the Z value of the root’s amount variable while in play mode in the editor by clicking and dragging in the inspector:

41794-recursiverotationanim.gif

Enjoy!