There is such a snake manual by Noobtuts
I made a snake on it, everything is fine, I added different things from myself, but here’s the problem - the tail behaves incorrectly. Namely - after eating 3 "apples" starts to make holes in the tail, if the snake crawls horizontally, and the tail crawls with steps parallel to the body, if the snake crawls vertically. Visually on the video, YouTube. https://youtu.be/YR6lfFX5xEI
Snake code
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine.UI; public class Snake2: MonoBehaviour { public Text tt; int score = 0; public void ClickTestu() { dir = Vector2.up; // This code is executed every frame that the RepeatButton remains clicked } public void ClickTestd() { dir = -Vector2.up; // This code is executed every frame that the RepeatButton remains clicked } public void ClickTestl() { dir = Vector2.left; // This code is executed every frame that the RepeatButton remains clicked } public void ClickTestr() { dir = Vector2.right; // This code is executed every frame that the RepeatButton remains clicked } // Did the snake eat something? bool ate = false; // Tail Prefab public GameObject tailPrefab; List < Transform > tail = new List < Transform > (); Vector2 dir = Vector2.right; // Use this for initialization void Start() { InvokeRepeating("Move", 0.3 f, 0.3 f); } // Update is called once per frame void Update() { tt.text = "Score " + score; } void Move() { // Save current position (gap will be here) Vector2 v = transform.position; // Move head into new direction (now there is a gap) transform.Translate(dir); // Ate something? Then insert new Element into gap if (ate) { // Load Prefab into the world GameObject g = (GameObject) Instantiate(tailPrefab, v, Quaternion.identity); // Keep track of it in our tail list tail.Insert(0, g.transform); // Reset the flag ate = false; } // Do we have a Tail? else if (tail.Count > 0) { // Move last Tail Element to where the Head was tail.Last().position = v; // Add to front of list, remove from the back tail.Insert(0, tail.Last()); tail.RemoveAt(tail.Count - 1); } } void OnTriggerEnter2D(Collider2D coll) { // Food? if (coll.name.StartsWith("food")) { // Get longer in next Move call ate = true; // Remove the Food Destroy(coll.gameObject); score++; } // Collided with Tail or Border else { dir = -Vector2.up; // ToDo 'You lose' screen } } The question is how to avoid this and what to do so that the tail normally follows the head, cell by cell?