- Home /
Rotating a camera and his object like an airplane simulator
Hi All, i'm totally new to Unity, and what i'm trying to test in this moment is rotating a shape to have it to move like an airplane. For my first step i'm ignoring physics,rigidbodies and so on. What i want to achieve are these objectives: 1) when i move my mouse up, it has to go down (related to its facing) 2) when i move my mouse right it has to roll on its Z axis. I produced some code that doesn't work, the rotations looks randomly and from time to time it looks like it goes in gimbal lock.
Could please someone suggest me the correct direction to follow? Thank you.
this is the wrong code.
// rigidbody.AddForce( ( transform.forward ) * playerSpeed ); rotationZ = Input.GetAxis("Mouse X") * xSensitivity * 0.02f ; rotationX = Input.GetAxis("Mouse Y") * zSensitivity * 0.02f ;
Quaternion newRotation = new Quaternion( rotationX , 0 , rotationZ ,1);
if( (rotationZ != 0) || (rotationX != 0) ) { target.transform.rotation = Quaternion.Slerp(target.transform.rotation, newRotation , Time.deltaTime ); }
Answer by sneftel · Apr 28, 2011 at 09:20 PM
There's not much need for Slerp()ing here, if I'm understanding your requirements. Just call target.transform.Rotate(), with the euler angles based on your X and Z rotations. By default, Rotate() specifies the rotation relative to the current orientation, which is what you want for something like an airplane.
thank you for your answer, doesn't rotate with euler angle suffer of gimbal lock?
@Thor: Working directly with Euler angles can indeed introduce gimbal lock, but this won't be a problem when using Transform.Rotate() to apply local, incremental rotations on a per-update basis.
Indeed. Gimbal lock is a problem which is related to perturbing an orientation which is stored as Euler angles, not to representing that perturbation in terms of Euler angles. Unity internally uses Quaternions to represent object orientation, so this isn't a problem here.
Answer by Jesse Anders · Apr 28, 2011 at 09:13 PM
Your first problem is here:
Quaternion newRotation = new Quaternion( rotationX , 0 , rotationZ ,1);
The elements of a quaternion don't represent rotation angles in any direct way. Any good reference on quaternions will explain how the rotation is encoded, but suffice to say that you rarely (if ever) want to construct a quaternion directly or modify its elements directly when working with Unity.
I didn't look at your code too carefully beyond that, but I think the above is the first problem you'll want to address.
thank you for your answer, i'll check the question more deeply