Prevent Player from moving into opposite direction than he already is

Hi. I am currently trying to learn how to make simple games and right now i am trying to recreate snake with the help of a tutorial. Alltough the tutorial doesn’t show how to disable movements temporarily. For example: The snake shouldn’t be able to move to the left while already moving to the right because it will collide with itself.

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            _direction = Vector2.up;
        } else if (Input.GetKeyDown(KeyCode.S))
        {
            _direction = Vector2.down;
        } else if (Input.GetKeyDown(KeyCode.A))
        {
            _direction = Vector2.left;
        } else if (Input.GetKeyDown(KeyCode.D))
        {
            _direction = Vector2.right;
        }
    }

You can try to use an Enumeration to hold the state of which direction the player is going in. Then, when getting the input, you can check which states allow for which direction of movement.

First, put this outside of your class or make a new script entirely if you want:


    public enum PlayerDirection { UP, DOWN, LEFT, RIGHT }

Then for your class:


private PlayerDirection currentDirection;

void Update()
{
     if (Input.GetKeyDown(KeyCode.W))
     {
          switch (currentDirection)
          {
               case PlayerDirection.DOWN:
                        break;
               default:
                        _direction = Vector2.up;
                        break;
          }
     }
     else if (Input.GetKeyDown(KeyCode.S))
     {
          switch (currentDirection)
          {
               case PlayerDirection.UP:
                        break;
               default:
                        _direction = Vector2.down;
                        break;
          }
     }
     else if (Input.GetKeyDown(KeyCode.A))
     {
          switch (currentDirection)
          {
               case PlayerDirection.RIGHT:
                        break;
               default:
                        _direction = Vector2.left;
                        break;
          }
         
     }
     else if (Input.GetKeyDown(KeyCode.D))
     {
          switch (currentDirection)
          {
               case PlayerDirection.LEFT:
                        break;
               default:
                        _direction = Vector2.right;
                        break;
          }
     }
}

With this, it will check if it is currently going in the opposite direction. If it is, then it will do nothing, but if it isn’t then you will be able to change your direction as usual.