I'm a new programmer and I wanted to create a snake game for fun and to learn.
This is my code for movement:
private Vector2 _direction = Vector2.right;
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.D))
{
_direction = Vector2.right;
}
else if (Input.GetKeyDown(KeyCode.A))
{
_direction = Vector2.left;
}
}
I wanted to add a code that if the snake was moving up, it does not move down, or if it was moving left does not move right, and other directions.
And I wanted to know how to call arrows for movement.
So what do I do?
Thanks for helping <3 I just joined stack overflow :)
CodePudding user response:
private Vector2 _direction = Vector2.right;
int currentdirection = 1;
//0-up , 1-right, 2-down, 3-left
private void Update()
{
if (Input.GetKeyDown(KeyCode.W) && currentdirection != 2 )
{
_direction = Vector2.up;
currentdirection = 0;
}
else if (Input.GetKeyDown(KeyCode.S))
{
_direction = Vector2.down;
currentdirection = 2;
}
else if (Input.GetKeyDown(KeyCode.D))
{
_direction = Vector2.right;
currentdirection = 1;
}
else if (Input.GetKeyDown(KeyCode.A))
{
_direction = Vector2.left;
currentdirection = 3;
}
}
This is the start of a simple solution. It has an int that keeps track of the direction the snake is moving. The if statement at the top has been modified to only change direction if the W key is pressed AND the current direction is not down. You can add something similar to the other three if statements.