134 lines
3.6 KiB
C#
134 lines
3.6 KiB
C#
using System.Collections.Generic;
|
|
using TEngine;
|
|
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>();
|
|
|
|
GameEvent.AddEventListener<bool>(ARGameSnackInterface_Event.IsStart,IsStart);
|
|
|
|
GameEvent.AddEventListener<float>(ARGameSnackInterface_Event.ControlRotion,ControlRotion);
|
|
}
|
|
|
|
public void IsStart(bool isStarted)
|
|
{
|
|
if (isStarted)
|
|
{
|
|
InvokeRepeating("Move", 0.0f, 1f);
|
|
|
|
SpawnFood();
|
|
}
|
|
else
|
|
{
|
|
CancelInvoke("Move");
|
|
|
|
// 清空食物list
|
|
FoodList.Clear();
|
|
}
|
|
}
|
|
|
|
public void ControlRotion(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);
|
|
|
|
GameEvent.Get<ARGameSnackInterface>().IsGrow(true);
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
}
|