最终界面
第一要创建敌人,我这里创建的是立方体(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的应用:

如果想要主角可以跨坡度移动,可以通过调整半径以及高度来实现
注:此篇文章是参考的一位大佬的文章写出来的,因为比较久了记不住是谁写的所以暂没有出处,请理解,本人写这篇文章只要是为了自己有个笔记
本文介绍了在Unity3D中如何使用NavMeshAgent组件为游戏角色实现自动寻路功能,以及如何通过鼠标点击控制主角移动。首先创建立方体作为敌人,并添加NavMeshAgent组件,设置目标点使其自动寻路。接着,扩展了主角的移动控制,当鼠标左键点击时,主角将移动到鼠标指针所在位置。同时,讨论了调整NavMeshAgent参数以允许角色跨越不同坡度的方法。
66

被折叠的 条评论
为什么被折叠?



