-1
\$\begingroup\$

Code:

function Start(){

  Cursor.lockState=CursorLockMode.Locked;

}

function OnGUI () {

  transform.Rotate(0,Input.GetAxis("Mouse X"),0);
  transform.Rotate(Input.GetAxis("Mouse Y"),0,0);
  transform.rotation.z=0;

}

But the rotation along z axis is not changing to zero.

\$\endgroup\$
  • \$\begingroup\$ OnGUI is called for rendering and handling GUI events, so you should better put this in the Update function anyways. And put the "transform.rotation.z=0;" line in the Start() function as it doesn't have to be called every frame but only once. \$\endgroup\$ – Shashimee Jul 6 '17 at 7:18
  • \$\begingroup\$ @Shashimee transform.rotation.z = 0 can't just move to Start() — the lines before it can modify z, for 2 reasons that may not be obvious. 1) Rotation axes aren't globally orthogonal: combinations of x&y rotations can yield z rotations (see link above for examples) 2) transform.rotation.z is not a z axis rotation angle. It's one of the imaginary components of a quaternion, representing the z component of the rotation axis scaled by the sine of half the rotation angle. It's not meaningful to change alone. transform.eulerAngles is closer, but still not a universal fix. Rotations are weird \$\endgroup\$ – DMGregory Jul 6 '17 at 23:37
0
\$\begingroup\$

First of all, i believe you meant to use Update instead of OnGui;

Since altering a transform's position/rotation have implicity implications in phisics, every time you alter them, there's a bunch of callbacks inside Unity, mainly, OnTransformChanged()/OnRotationChanged(). So, every time you change the transform, do it only once, that's why Unity will not allow you to assign their values individually like this:

transform.position = new Vector3(0,0,0); // for example, instead of 

transform.position.x = 0;
transform.position.x = 0;
transform.position.x = 0;

And you also need to use

transform.rotation = Quaternion.Euler (new Vector3 (bla,ble,0) ); 

to change a transforms angle.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.