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


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

snakeimg

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 surroundingScreen Shot 2015-03-06 at 12.50.13 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.

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


Leave a comment

Your email address will not be published. Required fields are marked *

19 thoughts on “2D Snake Clone Game Tutorial – Unity3D (C#)

  • Tadej

    Hey, great tutorial, could you please tell me, how to add that loosing screen, when you hit a border or snake’s tail. I would really appreciate your answer! 🙂

    • Mocha Post author

      Create a new scene and edit it as a final scene. Add an “else” after if and write “Application.LoadLevel(scenelevel);” which means if snake hits anything except the food, then load the level ordered scenelevel. You can see the order of scene in built menu.

      • khaled farouk

        thanks sir for your quick reply
        i want the snake as example Translate from right border to lift border and not crash

        i send you sir all my script to see how the game play , so what can i write in script to achieve this condition

        using UnityEngine;
        using System.Collections;
        using System.Collections.Generic;

        public class Snake : MonoBehaviour {

        Vector2 direction=new Vector2(1,0);
        public GameObject food,tailPiece;
        List tail=new List();
        bool ate=false;
        int score;

        // Use this for initialization
        void Start () {
        tail.Insert(0,Instantiate (tailPiece, new Vector2 (-1, 0), Quaternion.identity) as GameObject);
        tail.Insert(1,Instantiate (tailPiece, new Vector2 (-2, 0), Quaternion.identity)as GameObject);
        Instantiate (food, new Vector2 (15, 15), Quaternion.identity);
        InvokeRepeating (“move”, 2f, .1f);
        }

        // Update is called once per frame
        void Update () {
        if (Input.GetKeyDown (KeyCode.RightArrow)&& direction != new Vector2(-1,0))
        direction = new Vector2 (1, 0);
        if (Input.GetKeyDown (KeyCode.LeftArrow)&& direction != new Vector2(1,0))
        direction = new Vector2 (-1, 0);
        if (Input.GetKeyDown (KeyCode.UpArrow)&& direction != new Vector2(0,-1))
        direction = new Vector2 (0, 1);
        if (Input.GetKeyDown (KeyCode.DownArrow)&& direction != new Vector2(0,1))
        direction = new Vector2 (0, -1);
        }

        void OnTriggerEnter2D(Collider2D col){
        if (col.name.StartsWith (“food”)) {
        ate = true;
        score++;
        Destroy (col.gameObject);
        Instantiate (food, new Vector2 (Random.Range(-29,29), Random.Range(-19,19)), Quaternion.identity);
        if (col.name.StartsWith (“vector2”)){
        ate = true;
        Destroy (col.gameObject);
        Instantiate (food, new Vector2 (Random.Range(-29,29), Random.Range(-19,19)), Quaternion.identity);

        }
        } else {
        CancelInvoke ();
        print(“Score:”+ score);
        }
        }

        void move(){
        Vector2 pos = transform.position;
        transform.Translate (direction);
        if (ate) {
        tail.Insert (0, Instantiate (tailPiece, pos, Quaternion.identity) as GameObject);
        ate = false;
        } else {
        tail.Insert (0, tail [tail.Count – 1]);
        tail [0].transform.position = pos;
        tail.RemoveAt (tail.Count – 1);

        }
        }
        }

  • khaled farouk

    thanks sir for your quick reply
    i want the snake as example Translate from right border to lift border and not crash

    i send you sir all my script to see how the game play , so what can i write in script to achieve this condition

    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;

    public class Snake : MonoBehaviour {

    Vector2 direction=new Vector2(1,0);
    public GameObject food,tailPiece;
    List tail=new List();
    bool ate=false;
    int score;

    // Use this for initialization
    void Start () {
    tail.Insert(0,Instantiate (tailPiece, new Vector2 (-1, 0), Quaternion.identity) as GameObject);
    tail.Insert(1,Instantiate (tailPiece, new Vector2 (-2, 0), Quaternion.identity)as GameObject);
    Instantiate (food, new Vector2 (15, 15), Quaternion.identity);
    InvokeRepeating (“move”, 2f, .1f);
    }

    // Update is called once per frame
    void Update () {
    if (Input.GetKeyDown (KeyCode.RightArrow)&& direction != new Vector2(-1,0))
    direction = new Vector2 (1, 0);
    if (Input.GetKeyDown (KeyCode.LeftArrow)&& direction != new Vector2(1,0))
    direction = new Vector2 (-1, 0);
    if (Input.GetKeyDown (KeyCode.UpArrow)&& direction != new Vector2(0,-1))
    direction = new Vector2 (0, 1);
    if (Input.GetKeyDown (KeyCode.DownArrow)&& direction != new Vector2(0,1))
    direction = new Vector2 (0, -1);
    }

    void OnTriggerEnter2D(Collider2D col){
    if (col.name.StartsWith (“food”)) {
    ate = true;
    score++;
    Destroy (col.gameObject);
    Instantiate (food, new Vector2 (Random.Range(-29,29), Random.Range(-19,19)), Quaternion.identity);
    if (col.name.StartsWith (“vector2”)){
    ate = true;
    Destroy (col.gameObject);
    Instantiate (food, new Vector2 (Random.Range(-29,29), Random.Range(-19,19)), Quaternion.identity);

    }
    } else {
    CancelInvoke ();
    print(“Score:”+ score);
    }
    }

    void move(){
    Vector2 pos = transform.position;
    transform.Translate (direction);
    if (ate) {
    tail.Insert (0, Instantiate (tailPiece, pos, Quaternion.identity) as GameObject);
    ate = false;
    } else {
    tail.Insert (0, tail [tail.Count – 1]);
    tail [0].transform.position = pos;
    tail.RemoveAt (tail.Count – 1);

    }
    }
    }

    • Scotaire

      Never mind, if someone has the same problem : make the box colliders half the size of the snake! Did the trick for me.
      Thanks for this amazing tutorial.

  • Kuken

    Hello! I’m new in Unity (and programming in general) and I’m having a problem. The snake just doesn’t collide with the walls (and tail but I worry most for the former).

    UnassignedReferenceException: The variable Border_Left of Snake has not been assigned.
    You probably need to assign the Border_Left variable of the Snake script in the inspector.
    // I just changed all the border names to my preference

    I’ve already put the borders on the Snake script in inspector. Instead of just:
    public Transform Border_Top;

    I tried adding:
    = new Transform();

    but it says:
    Assets/Snake.cs(11,54): error CS0122: `UnityEngine.Transform.Transform()’ is inaccessible due to its protection level

    Still, the game is generally working with the Snake moving, eating, and growing properly! Thanks!