- Home /
Question by
watchieboy_unity · Jul 23, 2020 at 08:55 PM ·
2d2d game
Snake game doesn't respond to input
I have been trying to find what is wrong with my code for a while now. When I start the game it doesn't respond to any input. The first part of the snake is simply frozen in game. The variable "dir" doesn't change when I press down any of the WASD keys, which I find super strange. Why is this happening?
public class Head : MonoBehaviour
{
enum Direction
{
Up,
Down,
Left,
Right
}
public Snake snakePrefab;
List<Snake> snakeParts;
bool eatenApple;
Vector3 dirVector;
Direction dir;
void Start()
{
snakeParts = new List<Snake>();
StartCoroutine("MoveSnake");
}
//Make the snake move in the desired direction
private void Update()
{
//Register the key press to determine what direction the snake should be heading
if (Input.GetKeyDown(KeyCode.W))
{
dir = Direction.Up;
}
if (Input.GetKeyDown(KeyCode.A))
{
dir = Direction.Left;
}
if (Input.GetKeyDown(KeyCode.S))
{
dir = Direction.Down;
}
else
{
dir = Direction.Right;
}
Debug.Log(dir);
}
IEnumerator MoveSnake()
{
//Based on which keypress was registered in the update function, move the head of the snake accordingly
if (dir == Direction.Up)
{
transform.position += new Vector3(0, 1, 0);
}
if (dir == Direction.Down)
{
transform.position += new Vector3(0, -1, 0);
}
if (dir == Direction.Right)
{
transform.position += new Vector3(1, 0, 0);
}
if (dir == Direction.Left)
{
transform.position += new Vector3(-1, 0, 0);
}
//Move each part of the snake forward, and if an apple has been eaten, add an additional snakepart to the previous ending position of the snake
for (int i = 0; i < snakeParts.Count - 1; i++)
{
if (eatenApple)
{
Snake tailPart = (Snake)Instantiate(snakePrefab, snakeParts[i].transform.position, Quaternion.identity);
snakeParts.Add(tailPart);
eatenApple = false;
}
snakeParts[i].transform.position = snakeParts[i + 1].transform.position;
}
yield return new WaitForSeconds(0.1f);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Apple")
{
eatenApple = true;
}
}
}
Comment
Have you tried debugging if if (Input.GetKeyDown(Keycode.W)) actually registers a key press?
Your answer
Follow this Question
Related Questions
Creating 'redstone' like wires 1 Answer
Structuring complex 2D sprite animation 0 Answers
Level design clone of King of Thieves 0 Answers
Horizontal attraction? 0 Answers
trail renderer shows above everything (Unity 2D sorting layer ) 0 Answers