Object rotates only up to 90º and then backwards when using euler angles?

Hi there…
apply this function to a 3d object and observe.

when you’re moving the cursor from left to right, it works fine until 90º, but then your objects starts rotating backwards until it hits 270º. How can I do a linear rotation? :confused:

var targetRotation;
function Update()
{
	targetRotation=Input.mousePosition.x;
	transform.eulerAngles.x=targetRotation;
	print(targetRotation);
}

Oh, should’ve read the Documentation about the eulerangle thingy :slight_smile:

“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”

eulerAngles only work in the -360…360 degrees. If you want unlimited rotation, you can use the angle modulo 360:

var targetRotation;
function Update()
{
    targetRotation=Input.mousePosition.x % 360;
    transform.eulerAngles.x=targetRotation;
    print(targetRotation);
}

But this can produce weird rotations after some time: when you set eulerAngles.x, Unity internally reads transform.rotation, calculates the equivalent eulerAngles, modify the x component, convert it back to quaternion and store the result in transform.rotation, accumulating errors each time.

To avoid this, always set eulerAngles at once, like this:

var euler: Vector3;

function Start(){
    euler = transform.eulerAngles; // get the initial eulerAngles
}

function Update(){
    euler.x = Input.mousePosition.x % 360; // modify only the angle you want
    transform.eulerAngles = euler; // then set the actual eulerAngles
    print(euler.x);
}