最终界面
第一要创建敌人,我这里创建的是立方体(cube),将敌人添加网格代理组件
敌人代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class cube : MonoBehaviour
{
// Start is called before the first frame update
public Transform goal; //这个是目标,也就是主角
private NavMeshAgent agent; //调用代理
void Update()
{
agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;//到这里实现了自动寻路的功能
}
}
扩展,怎么实现鼠标控制主角移动
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Actor : MonoBehaviour
{
public Transform goal;
//这里是一个空节点,主要作用是获取坐标,即游戏开始没有操作的情况下目的地
private NavMeshAgent agent;
void Start()
{
agent = GetComponent<NavMeshAgent>();
agent.destination = goal.position;//到这里实现了自动寻路的功能
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
agent.destination = hit.point;//到这里实现移动到鼠标位置的功能
}
}
}
}
拓展,对于NavMeshAgent的应用:
如果想要主角可以跨坡度移动,可以通过调整半径以及高度来实现
注:此篇文章是参考的一位大佬的文章写出来的,因为比较久了记不住是谁写的所以暂没有出处,请理解,本人写这篇文章只要是为了自己有个笔记