How do I stop transform.Rotate() when it gets a new input.

Hi, i’m using transform.Rotate() to rotate my player character. Here is the code:

public float forwardSpeed = 75f;
public float lookSpeed = 75f;
public float twistSpeed = 75f;

private float pitch = 0;
private float yaw = 0;

void FixedUpdate ()
{
    float twist = 0;

    if (Input.GetKey(KeyCode.Q))
    {
        twist += twistSpeed * Time.fixedDeltaTime;
    }

    if (Input.GetKey(KeyCode.E))
    {
        twist -= twistSpeed * Time.fixedDeltaTime;
    }

    transform.Rotate(new Vector3(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0), lookSpeed * Time.fixedDeltaTime ,Space.Self);
    transform.Rotate(new Vector3(0, 0, twist), Space.Self);

    transform.position += transform.forward * forwardSpeed * Time.fixedDeltaTime;
}

I used to have it without the lookSpeed * Time.fixedDeltaTime part, and it worked great, but I implemented this so that it would make it so that the player couldn’t instantly 180. It works well for accomplishing that goal but it won’t rotate based on the new input until it is done with the old one. Is there a better way to do this/fix this problem?

Thanks for any answers. I’m still pretty new to Unity

If you need added control over expressions within an update function you can use a Coroutine.

Do a Google search or watch a video on YouTube about this. There is a lot of documentation and tutorials to learn from.


An example of what a Coroutine looks like:

void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        Debug.Log("Waiting for princess to be rescued...");
        yield return new WaitUntil(() => frame >= 10);
        Debug.Log("Princess was rescued!");
    }

The above was taken straight off the Unity docs.


I could write one for your application, but that wouldn’t help you learn :wink:

Have fun,