- Home /
Problems rotating back to zero
Hi.
I recently created a script that made the player lean with middle mouse click and drag. The problem that appears, is that the player does not rotate back to zero (on the Z axis). It rotates closer to 0, but still far from it. I get a different number every time.
Here is the script causing this problem (sorry for the length):
var leaning : boolean = false;
var maximumLeft : float = -30;
var maximumRight : float = 30;
var currRotationZ : float = 0;
var rotationSpeed : float = -5;
var backToZeroSpeed : float = 2;
var smoothDampVelocity : float;
var maxSpeed : float = 5;
var mouseLookObj1 : Transform;
var mouseLookObj2 : Transform;
function Update () {
if(Input.GetMouseButton(2)){
leaning = true;
if(mouseLookObj1){
mouseLookObj1.GetComponent(MouseLook).enabled = false;
}
if(mouseLookObj2){
mouseLookObj2.GetComponent(MouseLook).enabled = false;
}
currRotationZ += Input.GetAxis("Mouse X") * rotationSpeed;
currRotationZ = Mathf.Clamp(currRotationZ, maximumLeft, maximumRight);
transform.localEulerAngles.z = currRotationZ;
}if(!Input.GetMouseButton(2)){
leaning = false;
if(mouseLookObj1){
mouseLookObj1.GetComponent(MouseLook).enabled = true;
}
if(mouseLookObj2){
mouseLookObj2.GetComponent(MouseLook).enabled = true;
}
}if(!leaning){
currRotationZ = Mathf.SmoothDamp(currRotationZ, 0, smoothDampVelocity, backToZeroSpeed);
transform.rotation.z = Mathf.SmoothDamp(transform.rotation.z, 0, smoothDampVelocity, backToZeroSpeed);
}
}
Thanks,
Luka.
Answer by Wolfram · Jun 28, 2012 at 12:32 PM
Don't modify transform.rotation.z
in your last line, that's a component of a Quaternion and has nothing to do with the Z axis. Use transform.localEulerAngles.z
, as you did above.
Thanks! I don't know what I was thinking... It works like a charm now!
Answer by aldonaletto · Jun 28, 2012 at 12:43 PM
You must not change transform.rotation.z directly like you're doing in the last line! transform.rotation is a quaternion, and its XYZ components are not the fancy angles you see in the field Rotation in the Inspector - those are actually the localEulerAngles.
Maybe changing transform.rotation.z in the last line to transform.localEulerAngles.z makes it work - but not so well, because setting localEulerAngles individually may produce "rotation leakage", and after some time your object is tilted at weird angles.