Search code examples
unity-game-enginemonodevelopunityscript

Rotating object via Vector 3 var


Here is my code:

#pragma strict

public var spinAxis : Vector3 = Vector3(0,45,90);

function Start () {

}

function Update () {
    // Slowly rotate the object around its X axis at 1 degree/second.
    transform.Rotate(spinAxis * Time.deltaTime);
}

I just want the cube to spin on two axes (in this case, y and z) but it spins on all three. I know I'm making some dumb mistake here. I can do it successfully by saying

transform.Rotate(new Vector3(0,0,100) * Time.deltaTime);

for example. But I'd like the axes to be available from the inspector.


Solution

  • This will do what you want:

    #pragma strict
    
    public var spinSpeed : Vector3 = Vector3(0,45,90); // Degrees per second per axis
    private var rotation = Vector3.zero;
    
    function Update ()
    {
        rotation += spinSpeed * Time.deltaTime;
        transform.rotation.eulerAngles = rotation;
    }
    

    The reason your code gives unexpected results is because I think you misread what the Transform.Rotate function does. It does not give you an axis and an amount to spin around like the spinAxis variable name suggests. That is achieved by Transform.RotateAround.

    If you use Transform.Rotate then the rotations are applied sequentially. But in the process the axes get mixed up. For instance if you first rotate 90 degrees on the Y-axis then the X- and Z-axes have switched place. Rotate sequentially on any two axes and the third one will always get involved like this. Using the above code you essentially reset or recreate the entire rotation every update which allows you to keep the uninvolved axis at 0.