DotRecast
DotRecast copied to clipboard
Pathfinding is going off the navmesh
I have a navmesh that looks like this
My pathfinding is causing the agent to walk through the water, which is the empty area in the center of the screenshot.
Any ideas what I am doing wrong? Here's my code for finding the path. I probably screwed something up, it wasn't easy trying to figure out how to actually find a path using DotRecast. Had to use OpenAI and a lot of trial and error to try and figure it out lol.
private unsafe void FindPath(DtNavMesh navMesh, PathRequest request)
{
var startPosition = new RcVec3f(request.StartPosition.x, request.StartPosition.y, request.StartPosition.z);
var endPosition = new RcVec3f(request.EndPosition.x, request.EndPosition.y, request.EndPosition.z);
var navQuery = new DtNavMeshQuery(navMesh);
// Find the start and end polygons on the navmesh
var filter = DtQueryNoOpFilter.Shared;
var halfExtents = new RcVec3f(2.0f, 4.0f, 2.0f); // Extent for search area
var startPolyResult = navQuery.FindNearestPoly(startPosition, halfExtents, filter, out var startPolyRef, out _, out _);
if (!startPolyResult.Succeeded())
{
this.LogError($"Failed to find start position reference: {startPolyResult}");
request.Failed();
return;
}
var endPolyResult = navQuery.FindNearestPoly(endPosition, halfExtents, filter, out var endPolyRef, out _, out var canReachTarget);
if (!endPolyResult.Succeeded())
{
this.LogError($"Failed to find end position reference: {endPolyResult}");
request.Failed();
return;
}
_pathCache.Clear();
var pathResult = navQuery.FindPath(startPolyRef,
endPolyRef,
startPosition,
endPosition,
filter,
ref _pathCache,
DtFindPathOption.AnyAngle
);
if (!pathResult.Succeeded())
{
this.LogError("Failed to find end position reference");
request.Failed();
return;
}
// Output the path as an array of points
Span<DtStraightPath> straightPath = stackalloc DtStraightPath[256];
navQuery.FindStraightPath(startPosition, endPosition, _pathCache, _pathCache.Count, straightPath, out var straightPathCount, 256, 0);
var resultPath = new NetVector3[straightPathCount];
for (int i = 0; i < straightPathCount; i++)
{
var pos = straightPath[i].pos;
resultPath[i] = new NetVector3(pos.X, pos.Y, pos.Z);
}
request.Success(resultPath, canReachTarget);
}