# Problem with Z rotation when rotating X and Y and the same time.

Hellow.

When I rotate X and Y and the same time. The Z angle also rotate. Which offset the Cannon position.

The purpose of the script is to change a Cannon angle on the horizontal and the vertical. As to let the player aim.

Here is the snippet of code.

``````var speedPos = 40;
var speedNeg = -40;

function Update () {

if(Input.GetButton("keyup")){
transform.Rotate(Time.deltaTime * speedPos, 0, 0, Space.Self);
}

if(Input.GetButton("keydown")){
transform.Rotate(Time.deltaTime * speedNeg, 0, 0, Space.Self);
}

if(Input.GetButton("keyright")){
transform.Rotate(0, Time.deltaTime * speedPos, 0, Space.Self);
}

if(Input.GetButton("keyleft")){
transform.Rotate(0, Time.deltaTime * speedNeg, 0, Space.Self);
}

}

``````

Thank you.

Edit : Here to be clearer.

Here is the first state of the cannon.

http://img409.imageshack.us/img409/1865/state01.jpg

But when you play around and move it around.

http://img708.imageshack.us/img708/9760/state02.jpg

It become tilted, due to the Z rotation axis is moved, even though Z is never ordered to move in the code. Z generally move when X and Y rotation values are both moved.

I hope it's clearer, the computer I'm working on do not allow me to put in on video. So if it's still not comprehensible, I'll capture a video later.

Because rotation is an operation dependent upon the origin and therefore the previous operations which change your origin, it is more challenging to order operations in this way and even more troubling when you consider the problem of gimbal lock. When you rotate about the x axis, the y and z axes will move and likewise, when you rotate about the y axis, the x and z axes will move.

This is why many rotations use world or parent space axes rather than local axes as they will not change as you rotate your object. Performing your rotations in world space (Space.World or eulerAngles) or about parent axes (localEulerAngles) should resolve your issue, depending on your setup.

To overcome the challenge of cumulative rotations throwing your axes off, the simple answer is to not have cumulative rotations and to simply set the rotation explicitly each time:

cannonAim.js

``````var speed : float = 40.0f;
private var eulers : Vector3;

function Start() {
eulers = transform.eulerAngles;
}

function Update() {
eulers.x -= Input.GetAxis("Vertical") * speed * Time.deltaTime;
eulers.y += Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.eulerAngles = eulers;
}
//Because we perform a new rotation and override the old one,
//there are no cumulative rotation problems.

``````

I've corrected the Error. I've create 2 control, one for vertical and one for horizontal rotation. On the object, I've set a parent to my Cannon. Set the Vertical control on the cannon and horizontal control to the parent. Set the relative to Self, and it work like a Charm. :)