I will explain how to make a 2D Snake game in this tutorial.At first, open Unity and crate a 2D project. In this project, we are going to use 3 different image such as snake, food and border. So, create these images before start.Import these images and create surrounding borders from border image with names top, bottom, right, left. Place your snake image into the scene. Don’t forget to add Rigidbody 2D and Box Collider 2D(IsTrigger is checked). Rigidbody scale of snake should be a little bit small than snake because we don’t want to hit snake to its tails.Create a C# script named Snake and attach it to your snake. Lets edit it. Firtsly, create public game objects:
Now, we will move and control our snake with keyboard arrows. We need a move function, some variables to edit movement and need to call move function at start with InvokeRepeating.
Press play button and test code. You may change speed and moveVector variables to optimise the movement speed.Next, we will create foods. Create a food prefab and add Box Collider 2D(Istrigger is checked). Food should spawn inside of borders. We will call spawn function in Start().
Test again. A food is created at start and snake moves around. Now, add collider function to collect food and create another one. In additional, we will add tail when collect a food.Add “using System.Collections.Generic” and “using System.Linq” collections to use list.
Now, snake moves, eats and grows but snake can move opposite direction while moving. Add 2 booleans and modify keyboard controls like this:
Lets understand clearly all code. We created snake, food and borders. Snake moves with InvokeRepeating() includes Movement(). We create foods with SpawnFood() function between the borders. Snake collects food with OnTriggerEnter() by detect name of collider. You can add “else” in OnTriggerEnter() after if statement to make that “if collider’s name is food, than collect it. Else, end game” which means if you hit borders or snake itself, end game. Also you can manage score in OnTriggerEnter().
You can download source code here.