How do I rotate my object back to the world's up direction whilst keeping it's forward direction?
Hi there,
I have a simple flying game that allows 360 degree flight. I'm trying to make it so that when the input axis are equal to zero (so the player is not touching the controls), the ship should auto-level itself so that the ship's Up rotation matches the world's Up direction, whilst maintaining the same forward facing direction (i.e. the Ship's Y rotation should probably not change, right?).
Here's a staged example of the desired rotation. The red arrow indicates the world's Up direction:
This essentially should allow the player to fly in 360 degrees while maintaining a sense of direction. Notice the ship's Up starts as the world's Left in the GIF.
I've tried a few methods to achieve this but I'm a bit stumped. I believe this is a math issue, as I know that a Quaternion.Lerp can handle smooth rotation. However when the ship is rotated to different values on the XYZ axes, how do I calculate the right rotation for each axis?
Move/Rotate code:
bool movingX;
bool movingY;
public float MaxSpeed = 20;
public float MinSpeed = 0.1f;
public float CurSpeed;
public float TurnSpeed = 15;
public float YSpeed = 10;
public float PitchSpeed = 10;
public float maxDegrees = 70;
Vector3 input;
Vector3 finalMove;
Vector3 rotation;
CharacterController cc;
Vector3 initialRot;
void Start()
{
cc = GetComponent<CharacterController>();
initialRot = new Vector3(0, 0, 0);
}
private void Update()
{
input.x = Input.GetAxisRaw("Horizontal2");
input.y = Input.GetAxisRaw("Vertical2");
//Accel and Decel
if (Input.GetButton("Fire1"))
{
CurSpeed += 0.5f;
}
if (Input.GetButton("Fire2"))
{
CurSpeed -= 0.5f;
}
CurSpeed = Mathf.Clamp(CurSpeed, MinSpeed, MaxSpeed);
}
void Move()
{
cc.Move(transform.forward * CurSpeed * Time.deltaTime);
}
void Rotate()
{
input.Normalize();
if(input != Vector3.zero)
{
rotation.y = input.x * TurnSpeed;
rotation.x = input.y * PitchSpeed;
transform.Rotate(rotation * Time.deltaTime);
}
else
{
/// Auto rotate code here? ///
}
}
void FixedUpdate()
{
Move();
Rotate();
}
Thanks so much for the help!