Disable Diagonal Move

Hey guys, I’m doing a simple move and want to disable the diagonal move.

I don’t have any idea how to do that. I’m using transform.Translate

This is the code

 public void Update()
        {
            if (Input.GetKey(KeyCode.RightArrow))
            {
                transform.Translate(Vector3.right *5 * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.LeftArrow))
            {
                transform.Translate(Vector3.right * -5 * Time.deltaTime);
            }

            if (Input.GetKey(KeyCode.UpArrow))
            {
                transform.Translate(Vector3.forward* -5 * Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.DownArrow))
            {
                transform.Translate(Vector3.forward * 5 * Time.deltaTime);
            }
        }

So basically, you want to only be able to move in one direction at a time?

Easiest solution is just to add an ‘else’ between each of your if-statements.

I would suggest you to do this:

     public void Update()
    {
    if(Input.GetAxis("Vertical")==0){
    if (Input.GetKey(KeyCode.RightArrow))
    {
    transform.Translate(Vector3.right *5 * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.LeftArrow))
    {
    transform.Translate(Vector3.right * -5 * Time.deltaTime);
    }
    }
    if(Input.GetAxis("Horizontal")==0){
    if (Input.GetKey(KeyCode.UpArrow))
    {
    transform.Translate(Vector3.forward* -5 * Time.deltaTime);
    }
    if (Input.GetKey(KeyCode.DownArrow))
    {
    transform.Translate(Vector3.forward * 5 * Time.deltaTime);
    }
    }
    }

Warning: This code is untested but in theory it should work.

Hope it helps.