_xiaofang/xiaofang/Assets/Script/npc/RecuseNpc.cs
2024-12-13 19:23:39 +08:00

170 lines
3.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.AI;
public enum Npcstate
{
idle,
dead,
run
}
public class RecuseNpc : MonoBehaviour
{
private NavMeshAgent navMeshAgent;//navmesh组件
public string npcId;
public static RecuseNpc instance;
public Button recusebtn;
private bool statebool = false;
private Animator anim;
public Npcstate nstate = Npcstate.dead;
private bool movebool = false;
public Transform target;
public Vector3 currentTarget;
// 存目的地的list
public List<Vector3> targetPoints = new List<Vector3>();
private void Awake()
{
instance = this;
//recusebtn = GameObject.Find("Canvas/Recuse").GetComponent<Button>();
anim = this.GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
// 初始化 NavMeshAgent 的一些属性
navMeshAgent.speed = 3.5f; // 设置速度
navMeshAgent.acceleration = 8f; // 设置加速度
navMeshAgent.angularSpeed = 120f; // 设置旋转速度
navMeshAgent.stoppingDistance = 1f; // 设置停止的距离
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Player")
recusebtn.gameObject.SetActive(true);
if (statebool) return;
other.GetComponent<CharacterInturn>().cha = this.gameObject ;
}
private void OnTriggerExit(Collider other)
{
recusebtn.gameObject.SetActive(false);
}
public void SetNPCInfo(string id)
{
npcId = id;
}
//npc状态
public void Setnpcstate()
{
movebool = true;
nstate = Npcstate.idle;
recusebtn.gameObject.SetActive(false);
Debug.Log( npcId + "被救");
}
//添加npc的目的地到list中
public void SetNpcDes(Vector3 tar)
{
//target.position = tar;
targetPoints.Add(tar);
}
private void Update()
{
// 继续处理NPC的状态和动画
switch (nstate)
{
case Npcstate.idle:
SetAni(2);
break;
case Npcstate.run:
movebool = true;
Run(currentTarget);
break;
case Npcstate.dead:
SetAni(0);
break;
}
if (targetPoints.Count > 0) // 确保列表中有目标点
{
currentTarget = targetPoints[0]; // 获取当前的目标点
nstate = Npcstate.run;
movebool = true;
float dis = Vector3.Distance(this.transform.position, currentTarget);
// 判断是否到达目标点
if (movebool && dis < 0.1f)
{
Debug.Log("到达目标点");
// 设置NPC状态
nstate = Npcstate.idle;
movebool = false;
// 达到目标后,从列表中移除该目标点
if (targetPoints.Count > 1)
{
targetPoints = RemoveDes();
}
else
{
targetPoints.Clear(); // 清空列表
}
}
}
}
//移除第一个点
public List<Vector3> RemoveDes()
{
List<Vector3> list = new List<Vector3>();
for(int i= 1;i<targetPoints.Count;i++)
{
list[i-1] = targetPoints[i];
}
return list;
}
public void Run(Vector3 target)
{
if (movebool)
{
SetAni(1);
navMeshAgent.SetDestination(target); // 使用 NavMeshAgent 设置目标点
}
}
public void SetAni(int x)
{
anim.SetInteger("state", x);
}
}