- Home /
Need help converting Euler-based rotation to Quaternion-based (gimbal lock).
I am working on a mouse-based flight model for a game, and I've run into an issue that I can't quite solve. I have a custom cursor used to direct the roll of the aircraft: the direction the mouse cursor is from the center of the screen describes the up vector of the aircraft.
// Rotate vehicle from mousePosition
var screenVec: Vector3 = Vector3(Input.mousePosition.x - sCenter.x, Screen.height-Input.mousePosition.y - sCenter.y, 0);
var tarAngle: float = (Mathf.Atan2(screenVec.y, screenVec.x)*Mathf.Rad2Deg)+90;
if (tarAngle < 0) tarAngle+= 360;
var sangle: float = Mathf.MoveTowardsAngle(transform.eulerAngles.z, -tarAngle, rollSpeed*Time.deltaTime);
transform.RotateAround(transform.position,transform.forward,-tarAngle-sangle);
In addition, I have the aircraft pitch in the direction of its up vector depending on how far from the center of the screen the mouse cursor is (I have this bound to Input keys at the moment so that I can test it... same with forward motion):
// Determine pitchSpeed var newPitch: float = Vector3.Distance(screenVec,Vector3.zero)/sCenter.y; newPitch = -Mathf.Min(newPitch, 1); if (newPitch > -.2) newPitch = 0; newPitch *= pitchSpeed * Time.deltaTime;
// Rotate and move plane var moveForward: float = Input.GetAxis("Vertical")*5; if (Input.GetKey("a")) transform.RotateAround(transform.position,transform.right,newPitch); transform.Translate(0,0,moveForward*Time.deltaTime);
I also have the Camera slaved to the plane (in a separate script attached to the camera):
var plr: GameObject;
function FixedUpdate () { var newPos: Vector3 = plr.transform.position - (plr.transform.forward*10) + (plr.transform.up * 2); transform.position = newPos; transform.LookAt(plr.transform); }
This all works well, except when the plane approaches completely nose-up or nose-down. Then I get gimbal-lock and the plane spins wildly (due to the mouse code). I don't know how I would create a Quat to describe the 2D vector rotation of the plane based on the mouse position (I've tried a straight conversion using Quaternion.Euler(0,0,sangle) and I get the same result).
If anyone could help me make this work using only Quats, maybe the gimbal lock will no longer be an issue (I assume that's the reason for using them in the first place)...
Thanks!
Answer by poncho · Apr 29, 2011 at 01:31 PM
if you want to change vector3 Euler angle to Quaternion, you can use the Quaternion.Euler(x,y,z); function, is the function i use, hope it helps
Thanks, but I mentioned in the post that when I tried that method, I still got gimbal lock (because, I suppose, the original angles were approaching zero or 180 before the conversion).