示例
一个跟着最近玩家走的 NPC:用 NavMesh 寻路,每帧把”最近的玩家位置”设为目的地。
注意:这是每台客户端各自模拟的(大家算出来基本一致)。如果要”一个 owner 权威、其他人看”的严格同步版本,把目的地通过 AeloriaNetworkShim 发给其他人。
using UnityEngine;
using UnityEngine.AI;
using Cilbox;
using Aeloria.Shims;
using Aeloria.Scripts.AeloriaSdk.Players;
[Cilboxable]
public class NpcFollow : MonoBehaviour
{
public NavMeshAgent agent;
public float stopDistance = 2f;
void Update()
{
IAeloriaPlayer nearest = AeloriaPlayersShim.Nearest(transform.position);
if (nearest == null || agent == null) return;
if (nearest.DistanceTo(transform.position) <= stopDistance)
{
agent.isStopped = true;
}
else
{
agent.isStopped = false;
agent.SetDestination(nearest.GetPosition());
}
}
}
stopDistance 内停下,避免贴着玩家抖;agent.SetDestination 每帧调用没问题,但只在目标明显变化时调用更省;