2D Snake Game Tutorial – Unity3D (C#),

Play Demo

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:

public class Snake : MonoBehaviour { public GameObject food; public Transform rBorder; public Transform lBorder; public Transform tBorder; public Transform bBorder; 1 2 3 4 5 6 7 public class Snake : MonoBehaviour { public GameObject food ; public Transform rBorder ; public Transform lBorder ; public Transform tBorder ; public Transform bBorder ;

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.

private float speed = 0.1f; Vector2 vector = Vector2.up; Vector2 moveVector; void Start () { InvokeRepeating("Movement", 0.3f, speed); } void Update () { if (Input.GetKey (KeyCode.RightArrow)) { vector = Vector2.right; } else if (Input.GetKey (KeyCode.UpArrow)) { vector = Vector2.up; } else if (Input.GetKey (KeyCode.DownArrow)) { vector = -Vector2.up; } else if (Input.GetKey (KeyCode.LeftArrow)) { vector = -Vector2.right; } moveVector = vector / 3f; } void Movement() { transform.Translate(moveVector); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 private float speed = 0.1f ; Vector2 vector = Vector2 . up ; Vector2 moveVector ; void Start ( ) { InvokeRepeating ( "Movement" , 0.3f , speed ) ; } void Update ( ) { if ( Input . GetKey ( KeyCode . RightArrow ) ) { vector = Vector2 . right ; } else if ( Input . GetKey ( KeyCode . UpArrow ) ) { vector = Vector2 . up ; } else if ( Input . GetKey ( KeyCode . DownArrow ) ) { vector = - Vector2 . up ; } else if ( Input . GetKey ( KeyCode . LeftArrow ) ) { vector = - Vector2 . right ; } moveVector = vector / 3f ; } void Movement ( ) { transform . Translate ( moveVector ) ; }

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().

public GameObject food; void Start () { SpawnFood(); } public void SpawnFood() { int x = (int)Random.Range (lBorder.position.x, rBorder.position.x); int y = (int)Random.Range (bBorder.position.y, tBorder.position.y); Instantiate (food, new Vector2 (x, y), Quaternion.identity); } 1 2 3 4 5 6 7 8 9 10 11 12 13 public GameObject food ; void Start ( ) { SpawnFood ( ) ; } public void SpawnFood ( ) { int x = ( int ) Random . Range ( lBorder . position . x , rBorder . position . x ) ; int y = ( int ) Random . Range ( bBorder . position . y , tBorder . position . y ) ; Instantiate ( food , new Vector2 ( x , y ) , Quaternion . identity ) ; }

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.

List tail = new List(); bool eat = false; void Movement() { Vector2 ta = transform.position; if (eat) { if (speed > 0.002){ speed = speed - 0.002f; } GameObject g =(GameObject)Instantiate(tailPrefab, ta, Quaternion.identity); tail.Insert(0, g.transform); Debug.Log(speed); eat = false; } else if (tail.Count > 0) { tail.Last().position = ta; tail.Insert(0, tail.Last()); tail.RemoveAt(tail.Count-1); } transform.Translate(moveVector); } void OnTriggerEnter2D(Collider2D c) { if (c.name.StartsWith("food")) { eat = true; Destroy(c.gameObject); SpawnFood(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 List tail = new List ( ) ; bool eat = false ; void Movement ( ) { Vector2 ta = transform . position ; if ( eat ) { if ( speed & gt ; 0.002 ) { speed = speed - 0.002f ; } GameObject g = ( GameObject ) Instantiate ( tailPrefab , ta , Quaternion . identity ) ; tail . Insert ( 0 , g . transform ) ; Debug . Log ( speed ) ; eat = false ; } else if ( tail . Count & gt ; 0 ) { tail . Last ( ) . position = ta ; tail . Insert ( 0 , tail . Last ( ) ) ; tail . RemoveAt ( tail . Count - 1 ) ; } transform . Translate ( moveVector ) ; } void OnTriggerEnter2D ( Collider2D c ) { if ( c . name . StartsWith ( "food" ) ) { eat = true ; Destroy ( c . gameObject ) ; SpawnFood ( ) ; } }

Now, snake moves, eats and grows but snake can move opposite direction while moving. Add 2 booleans and modify keyboard controls like this:

bool vertical = false; bool horizontal = true; void Update () { if (Input.GetKey (KeyCode.RightArrow) && horizontal) { horizontal = false; vertical = true; vector = Vector2.right; } else if (Input.GetKey (KeyCode.UpArrow) && vertical) { horizontal = true; vertical = false; vector = Vector2.up; } else if (Input.GetKey (KeyCode.DownArrow) && vertical) { horizontal = true; vertical = false; vector = -Vector2.up; } else if (Input.GetKey (KeyCode.LeftArrow) && horizontal) { horizontal = false; vertical = true; vector = -Vector2.right; } moveVector = vector / 3f; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 bool vertical = false ; bool horizontal = true ; void Update ( ) { if ( Input . GetKey ( KeyCode . RightArrow ) & amp ; & amp ; horizontal ) { horizontal = false ; vertical = true ; vector = Vector2 . right ; } else if ( Input . GetKey ( KeyCode . UpArrow ) & amp ; & amp ; vertical ) { horizontal = true ; vertical = false ; vector = Vector2 . up ; } else if ( Input . GetKey ( KeyCode . DownArrow ) & amp ; & amp ; vertical ) { horizontal = true ; vertical = false ; vector = - Vector2 . up ; } else if ( Input . GetKey ( KeyCode . LeftArrow ) & amp ; & amp ; horizontal ) { horizontal = false ; vertical = true ; vector = - Vector2 . right ; } moveVector = vector / 3f ; }

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.

©Coffee Break Codes – 2D Snake Game Tutorial – Unity3D (C#)