我在这里分享我的AI路径查找脚本。我希望我的AI在游戏开始时走向一个目标(destination)。然而,当AI与某个特定对象发生碰撞(通过标签“bullet”查找)时,我希望设置一个新的目标。虽然代码没有报错,但在播放时,AI会前往第一个目标然后停在那里,即使它在途中与特定对象发生了碰撞。
有人能帮我看看吗?
using System.Collections;using System.Collections.Generic;using UnityEngine;using Pathfinding; public class AIPathfinding : MonoBehaviour { [SerializeField] public Transform target; [SerializeField] public Transform target2; [SerializeField] public float speed = 200f; [SerializeField] public float nextWayPointDistance = 3f; [SerializeField] Path path; [SerializeField] int currentWaypoint = 0; [SerializeField] bool reachedEndOfPath = false; [SerializeField] Seeker seeker; [SerializeField] Rigidbody2D rb; // Start is called before the first frame update void Start() { seeker = GetComponent<Seeker>(); rb = GetComponent<Rigidbody2D>(); InvokeRepeating("UpdatePath", 0f, 0.5f); } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag == "bullet") { UpdatePath(target2); } } public void UpdatePath(Transform target2) { if (seeker.IsDone()) { seeker.StartPath(rb.position, target.position, OnPathComplete); } } void OnPathComplete(Path p) { if (!p.error) { path = p; currentWaypoint = 0; } } void Update() { if (path == null) { return; } if (currentWaypoint >= path.vectorPath.Count) { reachedEndOfPath = true; return; } else { reachedEndOfPath = false; } Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized; Vector2 force = direction * speed * Time.deltaTime; rb.AddForce(force); float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]); if (distance < nextWayPointDistance) { currentWaypoint++; } } }
回答:
我的猜测是你从未停止Coroutine InvokeRepeating(“UpdatePath”, 0f, 0.5f)。因此,当子弹击中时,请调用CancelInvoke(),并更改seeker的目标(再次启动InvokeRepeating(…))。
我假设在函数seeker.SetTarget()中调用了NavMeshAgent.SetDestination(Vector3 position)。并且以某种方式计算并设置了Path。
你也可以将Update Path的主体移动到Update函数中,或者从那里调用它。不必考虑间隔。或者在你自定义的间隔中调用它。只需计算下一次你想调用的时间,如果下一次更新路径时间(Time.time加上你的冷却时间)小于Time.time,则调用它并计算下一次更新路径时间。