131 lines
3.5 KiB
C#

using System.Collections.Generic;
using UnityEngine;
namespace GameLogic
{
public class Snack : MonoBehaviour
{
private Rigidbody rb;
public GameObject bodyList;
public GameObject foodList;
public GameObject foodperfab;
public GameObject snackbodypre;
public float step = 1;
public float Speed = 10f;
public float spawnrange = 5f;
private Vector3 currentDirection = Vector3.forward;
List<Transform> BodyList = new List<Transform>();
List<GameObject> FoodList = new List<GameObject>();
void Start()
{
rb = GetComponent<Rigidbody>();
InvokeRepeating("Move", 0.0f, 1f);
SpawnFood();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
RotationCube(90);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
RotationCube(-90);
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
Grow();
}
}
private void RotationCube(float angle)
{
transform.Rotate(Vector3.up, angle);
currentDirection = transform.forward;
}
private void Move()
{
Vector3 previousHeadPosition = rb.position;
Vector3 movement = currentDirection * Speed * step * Time.fixedDeltaTime;
rb.MovePosition(rb.position + movement);
for (int i = BodyList.Count - 1; i > 0; i--)
{
BodyList[i].position = BodyList[i - 1].position;
}
if (BodyList.Count > 0)
{
BodyList[0].position = previousHeadPosition;
}
}
private void Grow()
{
GameObject body = GameObject.Instantiate(snackbodypre);
body.transform.parent = bodyList.transform;
if (BodyList.Count == 0)
{
body.transform.position = transform.position - currentDirection;
}
else
{
Transform lastBody = BodyList[BodyList.Count - 1];
body.transform.position = lastBody.position - lastBody.forward;
}
BodyList.Add(body.transform);
}
private void SpawnFood()
{
for (int i = FoodList.Count - 1; i >= 0; i--)
{
if (FoodList[i] == null)
{
FoodList.RemoveAt(i);
}
}
if (FoodList.Count == 0)
{
Vector3 randomPosition = new Vector3(
Random.Range(-spawnrange, spawnrange),
0f,
Random.Range(-spawnrange, spawnrange)
);
GameObject food = Instantiate(foodperfab, randomPosition, Quaternion.identity);
food.transform.parent = foodList.transform;
FoodList.Add(food);
}
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Food"))
{
FoodList.Remove(other.gameObject);
Destroy(other.gameObject);
SpawnFood();
Grow();
}
}
}
}