How to fix the rotation and Orientation in an object as a Children ?


I'm working in this Robot-Toy, I am trying to fix the rotation of the arm, but the Arm rotates keeping the same orientation don't change (always see to the same direction).

(The Base's Arm (in color green) rotates well, but the Arm as a "children" rotates keeping the same orientation)

Please take a look to the image.

alt text alt text

Here it is the Script I am using for the base in green color.

var gunSpeedNeg: int = -40;
var gunSpeedPos: int = 40;
function Update () {

    transform.Rotate(Vector3.right* gunSpeedNeg* Time.deltaTime);

    transform.Rotate(Vector3.right* gunSpeedPos* Time.deltaTime);


And here it is the script for the arm " who has to rotate according to the arm but it doesn't (It rotates but always keeping the same orientation)

var gunSpeed : float = 40;

private var rotation : Quaternion = Quaternion.identity;
private var left : Quaternion = Quaternion.AngleAxis(-150, Vector3.up);
private var right : Quaternion = Quaternion.AngleAxis(30, Vector3.up);

function Start ()
    // This piece of code will allow you to remember the origin.
    rotation = transform.rotation;
    left = rotation * left;
    right = rotation * right;

function Update () 
    var speed = gunSpeed * Time.deltaTime;

        rotation = Quaternion.RotateTowards(rotation, left, speed);

        rotation = Quaternion.RotateTowards(rotation, right, speed);

    transform.rotation = rotation;

Any advice is welcome.

Your code should rotate the whole hierarchy. It sounds to me that your children have some code affecting their world rotation somehow. Are there other scripts involved?

  1. Make sure your hierarchy is nested, not flat. You might have written code that set position to some joint manually, which would explain the behavior.
  2. Check all other scripts that can influence the rotation or position of the child parts to isolate the issue.

In your updated code you set rotation this way:

transform.rotation = rotation;

This sets the world rotation (absolute rotation) of the object. You likely want to set the local rotation, so hierarchy rotations are preserved. This is done simply.

transform.localRotation = rotation;

Likewise, you should store the localRotation in your Start function.

rotation = transform.localRotation;