2D Snake Game Tail Problems
Hello. I'm currently working on my first actual project to allow children to experience the games that preceded things like Mario and Legend of Zelda. I'm currently calling it 'Project Ancient Pack', and right now I'm working on a 2D snakes game that, right now, only has one player. However, I'm running into a problem where the tail, when the snake 'eats' an item, spawns the tail object but does not actually 'follow' the snake at the moment.
Currently, this is the script that I'm working on, based off of Coffee Break Codes' own snake game tutorial:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class Snake : MonoBehaviour
{
public Transform head;
List<Transform> tail = new List<Transform>();
public GameObject food;
public GameObject tailPrefab;
public Transform rBorder;
public Transform lBorder;
public Transform tBorder;
public Transform bBorder;
private float speed = 0.003f;
Vector2 dir = Vector2.up;
Vector2 moveVector;
bool ate = false;
bool horizontal = true;
bool vertical = false;
// Start is called before the first frame update
void Start()
{
Spawn();
InvokeRepeating("Move", 0.003f, speed);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.RightArrow) && horizontal)
{
horizontal = false;
vertical = true;
dir = Vector2.right;
}
else if (Input.GetKey(KeyCode.UpArrow) && vertical)
{
horizontal = true;
vertical = false;
dir = Vector2.up;
}
else if (Input.GetKey(KeyCode.LeftArrow) && horizontal)
{
horizontal = false;
vertical = true;
dir = -Vector2.right;
}
else if (Input.GetKey(KeyCode.DownArrow) && vertical)
{
horizontal = true;
vertical = false;
dir = -Vector2.up;
}
moveVector = dir / 3f;
}
void Move()
{
Vector2 ta = transform.position;
if (ate)
{
if (speed > 0.002)
{
speed = speed - 0.002f;
}
GameObject g = Instantiate(tailPrefab, ta, Quaternion.identity);
tail.Insert(0, g.transform);
Debug.Log(speed);
ate = false;
}
else if (tail.Count < 0)
{
tail.Last().position = ta;
tail.Insert(0, tail.Last());
tail.RemoveAt(tail.Count - 1);
}
transform.Translate(moveVector);
}
void Spawn()
{
//X position between the left and right borders
int x = (int)Random.Range(lBorder.position.x, rBorder.position.y);
//Y position between the top and bottom borders
int y = (int)Random.Range(bBorder.position.y, tBorder.position.y);
//initiate the food at (x, y)
Instantiate(food, new Vector2(x, y), Quaternion.identity); //Default Rotation
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.name.StartsWith("Food"))
{
ate = true;
Destroy(col.gameObject);
Spawn();
}
}
}
Everything works fine in this, save for the problem of the snake tail... dropping off like the blocks are doing mitosis.
Anyways, I'd like to know a good solution to this without changing what I already got.
Your answer
![](https://koobas.hobune.stream/wayback/20220612225524im_/https://answers.unity.com/themes/thub/images/avi.jpg)