在這里我分享我的 AiPathfinding 腳本。我希望我的 AI 在游戲開始時走到一個目的地(目標)。但是,當 AI 碰撞某個物件(使用 tag="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 ;
}
}
}
uj5u.com熱心網友回復:
我的猜測是您從未停止過協程 InvokeRepeating("UpdatePath", 0f, 0.5f)。所以一定要在子彈擊中時呼叫 CancelInvoke() 并更改搜索者的目標(再次啟動 InvokeRepeating(...))。
我假設 NavMeshAgent.SetDestination(Vector3 position) 在函式 seeker.SetTarget() 中被呼叫。并且以某種方式計算并設定路徑。
您也可以將 Update Path 的主體移動到 Update 函式中或從那里呼叫它。別介意間隔。或者在您的自定義時間間隔內呼叫它。只需計算下一次您想要呼叫它的時間,如果 nextUpdatePathTime(Time.time 加上您的冷卻時間)小于 Time.time,則呼叫它并計算下一個 nextUpdatePathTime。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393336.html
上一篇:在字典中似乎存在的鍵上獲取KeyNotFoundException
下一篇:如何在接觸墻壁后阻止玩家旋轉?
