AI徘徊状态似乎无法正常工作



我一直在尝试创造一个AI系统,它将遵循特定的路径点,一旦玩家角色进入触发区域,AI将开始追逐角色,反之亦然。

似乎有点像工作,但AI只移动到一个路径点,然后停止,直到玩家进入触发区域;在此之后,如果玩家走出去,它也只能走到一个航路点,然后再次停止。

我设置了多个路径点,我想让它一直循环下去,但它只走到其中一个路径点就停了下来。


using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor;
using UnityEngine;
using UnityEngine.AI;
using UnityEngineInternal;
public class AILocomotion : MonoBehaviour
{
public Transform playerTransform;
NavMeshAgent agent;
Animator animator;
public float maxTime = 1.0f;
public float maxDistance = 1.0f;
float timer = 0.0f;
bool moveTowards = false;
bool followWaypoint = false;
float deaccel= 0.5f;
float calVelocity = 0.0f;
public Transform[] points;
private int destPoint = 0;
public string animState;
void Start()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponent<Animator>();
moveTowards = false;
followWaypoint = true;  

}
// Update is called once per frame
void Update()
{
if (moveTowards == true)
{
timer -= Time.deltaTime;
if (timer < 0.0f)
{
float sqDistance = (playerTransform.position - agent.destination).sqrMagnitude;
if (sqDistance > maxDistance * maxDistance)
{
agent.destination = playerTransform.position;
}
}
animator.SetFloat("Speed", agent.velocity.magnitude);
}
else if (!moveTowards && agent.velocity.magnitude>0.0f)
{
calVelocity = agent.velocity.magnitude;
calVelocity -= Time.deltaTime * deaccel;
animator.SetFloat("Speed", calVelocity);
}

//CHECKS IF BOTH CONDITIONS HAVE MET AND RUNS THE WAYPOINT FOLLOWING CODE
if (followWaypoint == true && (!agent.pathPending && agent.remainingDistance < 1.0f))
{
GotoNextPoint();
}
Debug.LogError("Bool" + followWaypoint);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
moveTowards = true;
//DISABLES THE WAYPOINT FOLLOWING CODE TO RUN THE CHASE CODE INSTEAD
followWaypoint = false;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
moveTowards = false; 
//RE-ENABLES THE WAYPOINT FOLLOWING CODE ONCE THE PLAYER LEAVES THE TRIGGER AREA
followWaypoint = true;
}
}
//THIS IS THE WAYPOINT FOLLOWING CODE
void GotoNextPoint()
{
animator.SetFloat("Speed", agent.velocity.magnitude);
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
Debug.LogError("DestPoint = " + destPoint);
// Choose the next point in the array as the destination.
// cycling to the start if necessary.
destPoint = Random.Range(0, points.Length);
}
}

使用OnTriggerStay代替OntriggerEnter并尝试

最新更新