使用导航系统来实现鼠标点击控制人物移动
1. 导入素材
以小球机器人为例(Unity商店下载)
布置场景
2. 添加 Nav Mesh Agent 组件
更改红框里的参数即可
Steering | 操纵 |
---|---|
Speed | 寻路时的最大移动速度 |
Angular Speed | 寻路时的最大转向速度(最大角速度)。值越大,agent的转向越迅速。 |
Acceleration | 当agent寻路时的最大加速度。单纯物理意义上的加速度,控制速度变化的快慢。 |
Stopping Distance | 制动距离。当agent与目标点的距离小于它时会自动停下来以免越过目标点。 |
Auto Braking | 该属性设置为true时,agent会在到达Stopping Distance时直接停下。否则会出现当agent速度太快冲过目标点时,会缓慢的回到目标点的现象。 |
Radius | agent的躲避半径。相当于agent的私人空间,在这个半径内其它障碍或agent无法穿过。 |
Height | agent的高度。低于该值的障碍agent都无法穿过。。 |
Quality | 设置质量。我也不知道这个有什么用,设置成High Quality就好了。 |
priority | 优先级。低优先级的agent会给高优先级的agent让路。 |
想详细了解全部参数是什么意思可以看此文章!
https://blog.csdn.net/qq_37701948/article/details/105875160
3. 使用Navigation烘焙场景
打开Navigation面板
点击 Window - 点击倒是第二个 AI - 点击 Navigation
打开面板后按照以下操作进行设置
确保 Navigation Static 有被勾选
点击 Bake 开始烘焙
蓝色区域代表烘焙的区域
关于 Navigation 更多内容请看此
http://c.biancheng.net/view/2772.html
给Plane添加标签!
默认没有 Ground 标签,需要点 Add Tag 后点击 + 添加一个哦!
4. 敲移动代码!
创建 PlayerMove 脚本并拖给机器人
using UnityEngine.AI //需要添加命名空间才能调用NavMeshAgent
public class PlayerMove : MonoBehaviour
{
// 用于从射线投射获取信息
RaycastHit hitInfo;
private NavMeshAgent agent;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
// 创建从摄像机往鼠标点击的位置发射射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// 返回射线碰撞的物体的信息
Physics.Raycast(ray, out hitInfo);
// 鼠标右键点击且点击到的物体有碰撞体
if (Input.GetMouseButtonDown(1) && hitInfo.collider != null)
{
// 判断点击到的是地板
if (hitInfo.collider.gameObject.CompareTag("Ground"))
{
// 人物移动到点击到的坐标点
agent.destination = hitInfo.point;
}
}
}
}
官方API链接
Ray
Camera.ScreenPointToRay
RaycastHit
Physice.Raycast
6. 添加动画
创建 Animator Controller
拖给机器人并双击点开
创建 Blend Tree(混合树),创建后系统会默认执行
双击 Blend Tree 进入
左边添加一个 Float 类型的参数,命名为 Speed
点击 + 号添加两个参数
拖拽 Idle动画 和 Walk动画,注意动画是三角形符号的哦!
将 Parameter 设置成之前设置过的 Speed
在脚本中添加代码控制动画
在 Update 中添加
anim.SetFloat("Speed", agent.velocity.sqrMagnitude);
NavMeshAgent.velocity
Vector3.sqrMagnitude
完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PlayerMove : MonoBehaviour
{
// 用于从射线投射获取信息
RaycastHit hitInfo;
private NavMeshAgent agent;
private Animator anim;
private void Start()
{
agent = GetComponent<NavMeshAgent>();
anim = GetComponent<Animator>();
}
private void Update()
{
// 创建从摄像机往鼠标点击的位置发射射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// 返回射线碰撞的物体的信息
Physics.Raycast(ray, out hitInfo);
// 鼠标右键点击且点击到的物体有碰撞体
if (Input.GetMouseButtonDown(1) && hitInfo.collider != null)
{
// 判断点击到的是地板
if (hitInfo.collider.gameObject.CompareTag("Ground"))
{
// 人物移动到点击到的坐标点
agent.destination = hitInfo.point;
}
}
anim.SetFloat("Speed", agent.velocity.sqrMagnitude);
}
}
个人积累,有错误请多多包涵~
能帮到你是我的荣幸~