Simple Flying script (JS possibly)

Hi guys, i’ve a problem
I’ve tried to create a script that allows flying for my character, it’s pretty simple: press A or D: rotate around the Y axis
press W: rotate around the X axis so that my character looks up (45° max)
press S: rotate around the X axis so that my character looks down (-45° max)
all this while my character goes straight forward in the direction of transform.forward

This is the script i’ve written right now:

var speed : float = 20;

var rotX : float;
    
    function Update () {
    
    CC.Move(transform.forward * Time.deltaTime * speed);
    
    rotX=transform.rotation.x;
    
    if(Input.GetKey(KeyCode.A)) {
    transform.rotation.y=transform.rotation.y - (1 * Time.deltaTime);
    }
    
    if(Input.GetKey(KeyCode.D)) {
    transform.rotation.y=transform.rotation.y + (1 * Time.deltaTime);
    }
    
    if(Input.GetKey(KeyCode.W) && rotX>-0.25) {
    transform.rotation.x=transform.rotation.x - (1 * Time.deltaTime);
    }
    
    if(Input.GetKey(KeyCode.S) && rotX<0.25) {
    transform.rotation.x=transform.rotation.x + (1 * Time.deltaTime);
    }
    
    }

But here i got a problem: the rotations after a while mess a little, also the Z axis rotation changes and that creates a lot of problems. Also, i need that my charater can rotate more than 1 time around his Y axis, but with this code it can’t.

I hope someone of you can give me some adviices, and sorry if i’ve done some grammar errors. Thank you

This is because transform.rotation is the rotation in worldspace, as opposed to localspace, and operates with Quaternions which are difficult to wrap your head around unless you are a mathematician.

In short: World space rotation is regardless of your character’s alignment. World X remains constant, let’s call it north, whether or not your character is looking east, west, or northeast.

Use transform.localRotation.eulerAngles instead, it’s exactly the rotation the editor shows you.

For preventing values from going above bounds, use Mathf.Clamp(variablehere, minimum, maximum)