Tip - How to stop left rotation taking precedence

If like me, you like to get to the bottom of things, and need to understand the ‘how’, you will have asked how you can stop the left rotation taking precedence… Well heres how you do it :slight_smile:

Essentially, all you need is a flag for each rotation, that is set when the ship is currently rotating that way, you can then check this alongside the check for a button being held, if it is currently rotating left, it cant rotate right etc.

Hers how the code looks.

public class Rocket : MonoBehaviour
{
    bool _rotatingLeft = false;
    bool _rotatingRight = false;

    void Update()
    {
        ProcessInput();
    }

    void ProcessInput()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Debug.Log("Thrusting");
        }

        if (Input.GetKey(KeyCode.A) && !_rotatingRight)
        {
            _rotatingLeft = true;
            Debug.Log("Rotating Left");
        }
        else if (Input.GetKey(KeyCode.D) && !_rotatingLeft)
        {
            _rotatingRight = true;
            Debug.Log("Rotating Right");
        }
        else
        {
            _rotatingLeft = false;
            _rotatingRight = false;
        }
    }
}
4 Likes

Great workaround! I was tinkering with this as well but went with an if statement looking a bit like

    if (Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D))
    {
        Debug.Log("Rotating left/up");
    }
    else if (Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
    {
        Debug.Log("Rotating right/down");
    }

This worked but had the disadvantage that both A and D won’t register if pressed at the same time. Because of this I find your solution better.

Cheers!

Privacy & Terms