unity学习之自动寻径
来源:互联网 发布:windows snmp dhcp 编辑:程序博客网 时间:2024/04/19 20:25
今天我们主要学习了自动寻径。
我们要实现一个功能:点击场景中的一个位置,角色可以自动寻路过去。角色会绕过各种复杂的障碍,找到一条理论上”最短路径“。
主要步骤:
1、创建地形或地板都行。
2、增加角色。
3、添加障碍物。
4、选中地形或地板,打开window窗口的Navigation窗口,设置Navigation Static.
5、依次选中障碍物,重复上面的操作。
6、Navigation窗口中,选择Bake(烘焙)界面,点击Bake按钮,进行场景烘焙,就可以烘焙出寻路网格了。
7、为角色添加NavMeshAgent组件。Component->Navigation->Nav Mesh Agent。
8、给角色添加脚本。
脚本代码
- private NavMeshAgent agent;
- void Start() {
- agent = GetComponent<NavMeshAgent>();
- }
- void Update() {
- RaycastHit hit;
- if (Input.GetMouseButtonDown(0)) {
- Ray ray =
- Camera.main.ScreenPointToRay(Input.mousePosition);
- if (Physics.Raycast(ray, out hit)){
- agent.SetDestination(hit.point);
- }
- }
如果想加动画效果的话,可以通过Animator来实现,代码
- using UnityEngine;
- using System.Collections;
- public class Move : MonoBehaviour {
- private NavMeshAgent a;
- private Animator b;
- void Start () {
- a = GetComponent<NavMeshAgent>();
- b=GetComponent <Animator >();
- }
-
-
- void Update () {
- if (Input.GetMouseButtonDown(0))
- {
- Ray ray = Camera.main.ScreenPointToRay(Input .mousePosition );
- RaycastHit hit;
- if (Physics.Raycast(ray, out hit))
- {
- a.SetDestination(hit.point);
- }
- }
- if(a.remainingDistance ==0)
- {
- Idle();
- }
- else
- {
- Walk();
- }
- }
- void Idle()
- {
- b.SetFloat("idle", 1f);
- b.SetFloat("walk", 0.0f);
- b.SetFloat("run", 0.0f);
- }
- void Walk()
- {
- b.SetFloat("idle", 0.0f);
- b.SetFloat("walk", 1f);
- b.SetFloat("run", 0.0f);
- }
- void Run()
- {
- b.SetFloat("idle", 0.0f);
- b.SetFloat("walk", 0.0f);
- b.SetFloat("run", 1f);
- }
- }
如果想要让宠物跟随主人的话,只需在宠物身上加一个脚本
- public class Sphere : MonoBehaviour {
- public GameObject a;
- private NavMeshAgent agent;
- void Start () {
- agent = GetComponent<NavMeshAgent>();
- }
-
- // Update is called once per frame
- void Update () {
- if (a != null)
- {
- agent.destination = a.transform .position;
- }
- }
- }
0 0
- unity学习之自动寻径
- Unity学习之自动寻径
- Unity学习之自动寻径进阶
- Unity之自动寻径
- Unity之自动寻径
- unity之自动寻径
- unity之自动寻径
- Unity学习之巨魔自动寻径
- Unity之自动寻路
- Unity--自动寻径
- unity的学习----NavMeshAgent,自动寻路
- Unity 自动寻路Navmesh之入门
- Unity学习(10)之自动巡逻兵游戏
- Unity学习(11)之自动巡逻兵改进
- Unity3D学习之(自动寻径)
- 学习Unity3D之自动寻径。
- unity代码笔记<3>自动寻径
- Unity自动寻路
- 详解JavaScript模块化开发
- 详解jQuery内置函数map和each
- BIEE 11G 登陆时出现 “无法登录 验证期间出错” 的问题解决
- 详解js面向对象编程
- [Material Design] 打造简单朴实的CheckBox
- unity学习之自动寻径
- 说说 Rails 的套娃缓存机制
- Go语言总结和学习指南
- 读书笔记:《Version Control With Git》
- js实现页面跳转倒计时
- 遇到问题----jsp本机无乱码,部署到服务器上有乱码
- Halcon例程学习之距离变换(distance_transform)
- 调试 Nginx 的配置
- 谈谈“理论和空想”