Aligning to a specific axis (6 DOF Descent-like movement)

Hello, I've been trying to figure out how to replicate a movement of a ship like in the game Descent 1. What I understand is that it is a 6 DOF camera and they have some sort of auto-leveling implemented.

Right now I have 6 DOF movement in my game, but I cannot figure out how to get the ship to align to the up vector on each axis. For instance with this code:

/* Retrieve Input */
float yaw   = Input.GetAxis("Mouse X") * speed;
float pitch = Input.GetAxis("Mouse Y") * speed;

/* Get the axis rotation by raycasting a normal to the surface */
RaycastHit hitInfo;

if (Physics.Raycast(transform.position, -Vector3.up, out hitInfo, 400.0f))
   Quaternion rot = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);

   /* This is fine only if I do not rotate my ship 45 degrees upwards (or vice versa).
      But, I must support aligning to the floor in all 6 directions (including upside-down).
   transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y,
         rot.z, transform.rotation.w);

      transform.rotation = rot;  // Does not allow me to rotate my camera at all.
      transform.rotation *= rot; // Did not work.

/* Rotate camera */
transform.Rotate(Vector3.up, yaw);
transform.Rotate(Vector3.left, pitch);

This code will not align my ship properly in all rotations performed by the mouse. Is there some way to get this ship to align to the walls of my level no matter the rotation of the ship?

I'd appreciate any help, thanks.


transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y,
         rot.z, transform.rotation.w);

Won't do anything meaningful. The x, y, and z elements of the quaternion don't correspond to angles, and mixing and matching elements from different quaternions like that will just produce a more or less random result in the general case. (It might work out in some cases, but if so, it's just circumstantial.)


transform.rotation *= rot;

Is close, except it needs to be:

transform.rotation = rot * transform.rotation;

This will align the object instantly to the surface normal. If you want the alignment to be more gradual, you can use Quaternion.Slerp() instead.