【golang/navmesh】使用recast navigation进行寻路

目录

说在前面

  • go version:1.20.2 linux/amd64
  • 操作系统:wsl2
  • detour-go版本:v0.2.0
  • github:这里,求star!

安装

  • 使用go mod安装即可

    shell 复制代码
    go get github.com/o0olele/detour-go

使用

  • 使用场景模型构建navmesh

    • 通过recast navigation demo进行构建;构建完成后点击Save保存二进制文件
    • 通过在线工具构建;完成后点击Export as Recast NavMesh保存二进制文件
  • 使用detour-go加载二进制navmesh文件

    c 复制代码
    var mesh = loader.LoadTileMesh("./navmesh.bin")
    if mesh == nil {
    	panic("load mesh failed.")
    }
  • 进行寻路

    c 复制代码
    // 初始化nav mesh query
    var meshQuery = detour.DtAllocNavMeshQuery()
    var status = meshQuery.Init(mesh, 2048)
    if detour.DtStatusFailed(status) {
    	panic("init mesh query failed.")
    }
    
    // 初始化 query filter
    var meshFilter = detour.DtAllocDtQueryFilter()
    
    // 确定寻路起点
    var agentPos [3]float32
    var agentHalfExtents = [3]float32{1, 0.75, 1}
    var agentNearestPoly detour.DtPolyRef
    status = meshQuery.FindNearestPoly(agentPos[:], agentHalfExtents[:], meshFilter, &agentNearestPoly, agentPos[:])
    if detour.DtStatusFailed(status) {
    	panic("find closest point failed.")
    }
    
    // 确定寻路终点
    var agentTarget = [3]float32{1.1322085857391357, 10.197294235229492, -5.400757312774658}
    var agentTragetRef detour.DtPolyRef
    status = meshQuery.FindNearestPoly(agentTarget[:], agentHalfExtents[:], meshFilter, &agentTragetRef, agentTarget[:])
    if detour.DtStatusFailed(status) {
    	panic("find agent target closest point failed.")
    }
    
    // 寻路
    var path [256]detour.DtPolyRef
    var pathCount int
    meshQuery.FindPath(agentNearestPoly, agentTragetRef, agentPos[:], agentTarget[:], meshFilter, path[:], &pathCount, 256)
    
    // 详细路径
    var straightPath [256 * 3]float32
    var straightPathFlags [256]detour.DtStraightPathFlags
    var straightPathRef [256]detour.DtPolyRef
    var straightPathCount int
    meshQuery.FindStraightPath(agentPos[:], agentTarget[:], path[:], pathCount, straightPath[:], straightPathFlags[:], straightPathRef[:], &straightPathCount, 256, 0)
    fmt.Println(straightPath[:straightPathCount*3])

可视化

  • 复制examples/web下的文件

    shell 复制代码
    go run main.go
  • 在浏览器中访问http://localhost:9001/public

  • 点击LoadTileMesh,选择刚刚保存的二进制navmesh文件

  • 点击Add Agent,添加一个agent

  • 鼠标左键选择移动的目标点

相关推荐
牛奔1 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
寻星探路5 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
不老刘5 小时前
LiveKit 本地部署全流程指南(含 HTTPS/WSS)
golang·实时音视频·livekit
想用offer打牌6 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
lly2024067 小时前
Bootstrap 警告框
开发语言
2601_949146537 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
zmzb01038 小时前
C++课后习题训练记录Day98
开发语言·c++