How to make snake body from 3 parts? [snake game]
Now it have 2 parts, head and body. Head is one texture body is other texture (prefab). But i want create snake from 3 parts. Head, body (which will be longer after eating a food) and snake end which will be always the same. How to create a script for that?
There is snake script how looks like at now:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Snake : MonoBehaviour {
// Did the snake eat smthg?
bool ate = false;
// Tail Prefab
public GameObject tailPrefab;
//Current Movement Directions (by default it moves to the right)
Vector2 dir = Vector2.right;
// Use this for initialization
void Start () {
//Move the Snake every 300ms
InvokeRepeating ("Move", 0.3f, 0.3f);
}
// Update is called once per frame
void Update () {
// Move in a new directions
if (Input.GetKey (KeyCode.RightArrow))
dir = Vector2.right;
else if (Input.GetKey (KeyCode.DownArrow))
dir = -Vector2.up; //down becouse of -Vector
else if (Input.GetKey (KeyCode.LeftArrow))
dir = -Vector2.right; //left becouse of -Vector
else if (Input.GetKey (KeyCode.UpArrow))
dir = Vector2.up;
}
void Move(){
// Save current position (gap will be here)
Vector2 v = transform.position;
// Move head into new directions (now there is a gap)
transform.Translate (dir);
// Ate smthg? Then insert new Element in to gap
if (ate) {
// Load Prefab in to 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?
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);
}
}
// Keep track of Tail
List<Transform> tail = new List<Transform>();
void OnTriggerEnter2D(Collider2D coll){
// Food?
if (coll.name.StartsWith ("FoodPrefab")) {
// Get longer in next Move call
ate = true;
// Remove the food
Destroy (coll.gameObject);
}
// Collided with Tail or Border
else {
// ToDo "you lose" screen
}
}
}
Thanks for answers!