I am very new to Unity, and I am making a game where I need to be able to fly an airplane. I’ve been implementing the roll and yaw of the aircraft, and everything works, except when the x of the rotation reaches 90 - then the object is instantly rotated in all axes in a very strange way, and I can’t tell what part of my code does this. If you have the time to help, it would probably be good to apply the following code to a cube or something to see what I mean. Many thanks for any help!
public class PlayerMovement : MonoBehaviour
{
// Variables controlling roll of the aircraft;
private Vector3 rollRotation;
[SerializeField] private float rollSpeed = 100;
// Variables controlling yaw of the aircraft;
private Vector3 yawRotation;
[SerializeField] private float yawSpeed = 25;
private void FixedUpdate()
{
PlayerRoll();
PlayerYaw();
}
private void PlayerYaw()
{
if (Input.GetKey(KeyCode.A))
{
yawRotation = Vector3.down;
}
else if (Input.GetKey(KeyCode.D))
{
yawRotation = Vector3.up;
}
else
{
yawRotation = Vector3.zero;
}
Vector3 finalYawRotation = yawRotation * yawSpeed * Time.deltaTime;
Vector3 rot = transform.rotation.eulerAngles + finalYawRotation;
rot.y = ClampAngle(rot.y,-20f,20f);
transform.localRotation = Quaternion.Euler(rot);
float ClampAngle(float angle, float from, float to)
{
if (angle < 0f) angle = 360 + angle;
if (angle > 180f) return Mathf.Max(angle, 360 + from);
return Mathf.Min(angle, to);
}
}
private void PlayerRoll()
{
// Checks which direction to apply roll, if any, and then applies it;
if (Input.GetKey(KeyCode.Q))
{
rollRotation = Vector3.left;
}
else if (Input.GetKey(KeyCode.E))
{
rollRotation = Vector3.right;
}
else
{
rollRotation = Vector3.zero;
}
Vector3 finalRollRotation = rollRotation * rollSpeed * Time.deltaTime;
Vector3 rot = transform.rotation.eulerAngles + finalRollRotation;
transform.localRotation = Quaternion.Euler(rot);
}
}