1.在玩家和敌人上都添加组件Nav Mesh Agent。
2.地形,玩家和敌人,左上角的static都打上对钩。
3.点击Window选择AI然后点击Navigation.
4.然后点击Bake进行烘焙。
5.添加代码AI,挂载到敌人身上。Tarent上拖拽玩家。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class AI : MonoBehaviour
{
public GameObject target;
private NavMeshAgent navMeshAgent;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent>();
if (navMeshAgent == null)
{
navMeshAgent = gameObject.AddComponent<NavMeshAgent>();
}
navMeshAgent.stoppingDistance = 1.0f;
}
void Update()
{
navMeshAgent.SetDestination(target.transform.position);
}
}
这样就实现了自动寻路与自动追踪,移动玩家会发现敌人追踪玩家。