Not Pressing Two Buttons At The Same Time

Hello everyone, i have a question. I have a tank script which simply allows my tank to move forward, backward, left and right. But when i press for example forward and left at the same time, it goes cross to the left. I want to stop that, I simply want my tank not to move when player presses two buttons at the same time. Here is my code :

function Update () {


if (Input.GetKey("w")){
transform.eulerAngles = Vector3(0, 0, 0);
transform.Translate(Time.deltaTime*2.5,0,0,Space.World);
}


if (Input.GetKey("a")){
transform.eulerAngles = Vector3(0, -90, 0);
transform.Translate(0,0,Time.deltaTime*2.5,Space.World);

}

if (Input.GetKey("d")){
transform.eulerAngles = Vector3(0, 90, 0);
transform.Translate(0,0,Time.deltaTime*-2.5,Space.World);

}

if (Input.GetKey("s")){
transform.eulerAngles = Vector3(0, 180, 0);
transform.Translate(Time.deltaTime*-2.5,0,0,Space.World);

}

}

Thanks :slight_smile:

If you use if/else statements, only one of the keys will be processed at a time.

if ( Input.GetKey(KeyCode.A) ) {
    doStuffForA();
}

else if ( Input.GetKey(KeyCode.B) ) {
    doStuffForB();
}

/* etc... */

If you have to make sure that none of a specific group of keys are being pressed before processing the first key, you could do something like this to keep track of an array of keys that need to be checked:

This code uses an array to keep track of all the possible input keys.

It loops through the array to see if any of them are being pressed (other than the one passed in as a parameter).

You can populate the list of keys in the Inspector, which is nice.

var inputKeys  :  KeyCode [];

function isAnyOtherKeyPressed ( ignoreKey : KeyCode ) : boolean
{
    if ( ! inputKeys  ||  inputKeys.length == 0 ) {
        return false;
    }

    /* loop through each potential input key */

    for ( var theKey : KeyCode in inputKeys ) {
        if ( theKey != ignoreKey ) {
            if ( Input.GetKeyDown(theKey) ) {
                return true;
            }
        }
    }

    return false;
}

function Update ()
{
    if ( Input.GetKeyDown(KeyCode.A) ) {
        if ( ! isAnyOtherKeyPressed(KeyCode.A) ) {
            doStuffForA();
        }
    }

    else if ( Input.GetKeyDown(KeyCode.B) ) {
        doStuffForB();
    }

    /* etc... */

}

Just use some more conditional logic in your if statements. Do something like this for each of your if statements
if (Input.GetKey(“w”) && !Input.GetKey(“a”) && !Input.GetKey(“s”) && !Input.GetKey(“d”))