Unity to achieve simple Snake game

Time:2020-12-3

In this paper, we share the specific code of unity to achieve Snake game for your reference. The specific content is as follows

First, create a header and write a script to control the movement of the head by WASD.

Vector3 up=new Vector3(0,1,0);
Vector3 down=new Vector3(0,-1,0);
Vector3 left=new Vector3(-1,0,0);
Vector3 right=new Vector3(1,0,0);
Vector3 now; // actual head direction

  float timer=0f;
  float timerGap=0.1f;
  void Start () 
  {
    now = up;
  }
  void Update () 
  {
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.W))
    {
      now = up;
    }
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.S))
    {
      now = down;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.A))
    {
      now=left;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.D))
    {
      now = right;
    }

    timer += Time.deltaTime;

    if (timer > timerGap) 
    {
      //Move one unit in the current direction every 0.1s (0.5 is the head size).
      timer = 0;
      transform.position = 0.5f * now + transform.position;

    }

  }

And then you create the initial body, so that the body follows the head. The method is to put the body into an array, then the body with subscript 0 moves to the position before the head, and then the body with subscript i moves to the position of I-1.

Create the initial body and place it in the array.

Public GameObject body; // body preset
List<GameObject> snakeBody = new List<GameObject>(); 

  void Awake()
  {
    for (int i = 0; i < 3; ++i) 
    {
      GameObject newbodynext=Instantiate (body, 
      transform.position-(i+1)*new Vector3(0,0.5f,0),
      Quaternion.identity)as GameObject;
      snakeBody.Add (newbodynext);
    }
  }

Realize following

void Update () 
  {
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.W))
    {
      now = up;
    }
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.S))
    {
      now = down;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.A))
    {
      now=left;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.D))
    {
      now = right;
    }

    timer += Time.deltaTime;

    if (timer > timerGap) 
    {
      Vector3 tmpPosition =  transform.position ; // record the position of the head before the change
      List < vector3 > tmplist = new list < vector3 > (); // record the position before body change 

      for (int i = 0; i < snakeBody.Count; ++i) 
      {
        tmpList.Add (snakeBody [i].transform.position);
      }

      timer = 0;


      transform.position = 0.5f * now + transform.position;

      snakeBody [0]. transform.position  =Tmpposition; // move 0 before the head


      //Move your body forward in turn
      for (int i = 1; i < snakeBody.Count; ++i) 
      {
        snakeBody [i].transform.position = tmpList [i - 1];
      }

    }

}

After the initial snake is created, it begins to add food and grow the snake’s body. There are also detection of game failure, that is, hitting the body or boundary, using event triggered detection to complete.

Create food

Public GameObject foodprefab; // food preset
void Start () {
    now = up;

    createFood ();


  }

  void createFood()
  {

    float x = Random.Range(-6.5f, 6.5f);
    float y = Random.Range(-4.5f, 4.5f);          
    Instantiate(foodPrefab,new Vector3(x,y,0f),Quaternion.identity);
  }

Trigger detection

void OnTriggerEnter(Collider other) 
  {// the other is the collided body

    if (other.gameObject.tag.Equals("Food")) 
    {

      Destroy(other.gameObject);

      GameObject newbodynext = Instantiate (body,
      snakeBody[snakeBody.Count-1].transform.position,
      Quaternion.identity)as GameObject;

      snakeBody.Add  (newbodynext); // increases snake's body
      createFood();
    }
    else if(other.gameObject.tag.Equals("Body"))
    {
      SceneManager.LoadScene ("Snake",  LoadSceneMode.Single ); // restart
    }
  }


  void OnTriggerExit(Collider other)
  {
    if (other.gameObject.tag.Equals("Boundary")) 
      SceneManager.LoadScene("Snake", LoadSceneMode.Single);
  }

Complete code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class HeadMove : MonoBehaviour {



  public GameObject body;
  public GameObject foodPrefab;


  Vector3 up=new Vector3(0,1,0);
  Vector3 down=new Vector3(0,-1,0);
  Vector3 left=new Vector3(-1,0,0);
  Vector3 right=new Vector3(1,0,0);
  Vector3 now;


  float timer=0f;
  float timerGap=0.1f;

  List<GameObject> snakeBody = new List<GameObject>();  
  // Use this for initialization

  void Awake()
  {
    for (int i = 0; i < 3; ++i) 
    {
      GameObject newbodynext=Instantiate (body, transform.position-(i+1)*new Vector3(0,0.5f,0),Quaternion.identity)as GameObject;
      snakeBody.Add (newbodynext);
    }
  }
  void Start () {
    now = up;

    createFood ();


  }

  void createFood()
  {

    float x = Random.Range(-6.5f, 6.5f);
    float y = Random.Range(-4.5f, 4.5f);          
    Instantiate(foodPrefab,new Vector3(x,y,0f),Quaternion.identity);
  }

  // Update is called once per frame
  void Update () 
  {
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.W))
    {
      now = up;
    }
    if (now!=up&&now!=down&&Input.GetKey (KeyCode.S))
    {
      now = down;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.A))
    {
      now=left;
    }
    if (now!=left&&now!=right&&Input.GetKey (KeyCode.D))
    {
      now = right;
    }

    timer += Time.deltaTime;

    if (timer > timerGap) 
    {
      Vector3 tmpPosition = transform.position;
      List<Vector3> tmpList = new List<Vector3> (); 

      for (int i = 0; i < snakeBody.Count; ++i) 
      {
        tmpList.Add (snakeBody [i].transform.position);
      }

      timer = 0;


      transform.position = 0.5f * now + transform.position;

      snakeBody [0].transform.position = tmpPosition;


      for (int i = 1; i < snakeBody.Count; ++i) 
      {
        snakeBody [i].transform.position = tmpList [i - 1];
      }

    }

  }



  void OnTriggerEnter(Collider other) 
  {// the other is the collided body

    if (other.gameObject.tag.Equals("Food")) 
    {

      Destroy(other.gameObject);
      GameObject newbodynext = Instantiate (body,snakeBody[snakeBody.Count-1].transform.position,Quaternion.identity)as GameObject;
      snakeBody.Add (newbodynext);
      createFood();
    }
    //It's going to reduce the head to body radius of 4.0, so it's going to start touching the body
    else if(other.gameObject.tag.Equals("Body"))
    {
      SceneManager.LoadScene("Snake", LoadSceneMode.Single);
    }
  }


  void OnTriggerExit(Collider other)
  {
    if (other.gameObject.tag.Equals("Boundary")) 
      SceneManager.LoadScene("Snake", LoadSceneMode.Single);
  }
}

Mount the script on the head object, then add the body and food preset body, and then add the boundary.

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.