I am trying to make a snake game in which the snake eats apple and gets big but the snake is not moving
Why is the snake not moving?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnakeController : MonoBehaviour {
// Settings
public float MoveSpeed = 5;
public float SteerSpeed = 180;
public float BodySpeed = 5;
public int Gap = 10;
public GameObject FoodPrefab; // Add this line
// References
public GameObject BodyPrefab;
// Lists
private List<GameObject> BodyParts = new List<GameObject>();
private List<Vector3> PositionsHistory = new List<Vector3>();
// Start is called before the first frame update
void Start() {
GrowSnake();
GrowSnake();
GrowSnake();
GrowSnake();
GrowSnake();
}
// Update is called once per frame
void Update() {
// Move forward
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
// Steer
float steerDirection = Input.GetAxis("Horizontal"); // Returns value -1, 0, or 1
transform.Rotate(Vector3.up * steerDirection * SteerSpeed * Time.deltaTime);
// Store position history
PositionsHistory.Insert(0, transform.position);
// Move body parts
int index = 0;
foreach (var body in BodyParts) {
Vector3 point = PositionsHistory[Mathf.Clamp(index * Gap, 0, PositionsHistory.Count - 1)];
// Move body towards the point along the snakes path
Vector3 moveDirection = point - body.transform.position;
body.transform.position += moveDirection * BodySpeed * Time.deltaTime;
// Rotate body towards the point along the snakes path
body.transform.LookAt(point);
index++;
}
// Check for food
GameObject food = GameObject.FindWithTag("Food");
if (food != null) {
float distance = Vector3.Distance(transform.position, food.transform.position);
if (distance < 1.0f) {
Destroy(food);
GrowSnake();
}
} else {
SpawnFood();
}
}
private void GrowSnake() {
// Instantiate body instance and
// add it to the list
GameObject body = Instantiate(BodyPrefab);
BodyParts.Add(body);
}
private void SpawnFood() {
// Spawn food at a random position
Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f));
Instantiate(FoodPrefab, position, Quaternion.identity);
}
}