找回密码
 立即注册
查看: 744|回复: 0

Unity寻路插件(A* Pathfinding)进阶教程十五:从编辑器脚本查找路径

[复制链接]
发表于 2021-1-25 09:23 | 显示全部楼层 |阅读模式
本系列的教程文章基于 A*Pathfinding Project 4.2.8的官网教程翻译,每一章节的原文地址都会在教程最下方给出。
这篇文章讲如何在play mode之外让插件工作,譬如编辑器脚本。
编辑器模式下的寻路工作,其实就是指Unity在不点击Play运行时工作。其工作方式与在Play Mode下几乎相同,唯一的主要区别就是路径请求是同步的,即会立即计算它们。通常来说,路径请求都是异步的,甚至会分在几个帧内去完成。
若让插件工作,你首先必须要初始化整个路径查找系统。因为编辑器模式下,graphs是又能没被反序列化,并且graphs也没有被scan过的。AstarPath.FindAstarPath方法会保证AstarPath.active属性被正常设置,并且所有的graphs都被反序列化了。(它们的存储是一个byte数组)
// Make sure the AstarPath object has been loaded
AstarPath.FindAstarPath();

AstarPath.active.Scan();
如果你觉得一个graph可能已经被初始化了,但是不那么确定,(比如,你可能运行了一个特定脚本好多次了)那么你需要先检查一下,一个好的方式就是检查graph是否已经有node了。
// Check if the first grid graph in the scene has any nodes
// if it doesn't then it is not scanned.
if (AstarPath.active.data.gridGraph.nodes == null) AstarPath.active.Scan();
在这之后,你就可以像往常一样请求路径了。下面的示例展示了直接使用AstarPath组件。但其实使用Seeker组件也是没问题的。</p>ABPath path = ABPath.Construct(transform.position, target.position);
AstarPath.StartPath(path);
// Everything is synchronous so the path is calculated now

Debug.Log("Found a path with " + path.vectorPath.Count + " points. The error log says: " + path.errorLog);

// Draw the path in the scene view
for (int i = 0; i < path.vectorPath.Count - 1; i++) {
    Debug.DrawLine(path.vectorPath, path.vectorPath[i+1], Color.red);
}
原文地址:
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-25 04:39 , Processed in 0.063291 second(s), 22 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表