I’m encountering a problem where while applying penalties and walkability in my grid graph rule, the internal Vector3 coordinates tend to get the Z position wrong. X and Y are always correct, but the Z coordinate is usually -0.1, or worse, -1, which causes it to wrongly set walkable/unwalkable positions on my map. About every one of five nodes will have z = -0.1 or -1.
It looks like this happens completely randomly on completely random places of the map.
Here is the entire code used:
public sealed class Pathfinder {
private readonly Map _map;
private const float NODE_SIZE = 1f;
public Pathfinder(Map map) { _map = map; }
private AstarData _graphData;
private GridGraph _gridGraph;
public void Initialize() {
_graphData = AstarPath.active.data;
_graphData.ClearGraphs();
_gridGraph = (GridGraph) _graphData.AddGraph(typeof(GridGraph));
_gridGraph.is2D = true;
_gridGraph.center = new Vector3((float) _map.Size.x / 2, (float) _map.Size.y / 2, 0) -
new Vector3(0.5f, 0.5f, 0f);
_gridGraph.SetDimensions(_map.Size.x, _map.Size.y, NODE_SIZE);
_gridGraph.cutCorners = false;
_gridGraph.neighbours = NumNeighbours.Eight;
AstarPath.active.maxNearestNodeDistance = 1;
AstarPath.active.threadCount = ThreadCount.AutomaticLowLoad;
AstarPath.active.heuristic = Heuristic.Euclidean;
_gridGraph.rules.AddRule(new NodeTraversalGridGraphRule(_map));
AstarPath.active.Scan();
}
public void UpdateGraphNode(Vector3Int node) {
AstarPath.active.UpdateGraphs(new Bounds(node, Vector3.one));
AstarPath.active.FlushGraphUpdates();
}
}
public class NodeTraversalGridGraphRule : GridGraphRule {
private readonly Map _map;
public NodeTraversalGridGraphRule(Map map) { _map = map; }
public override void Register(GridGraphRules rules) {
rules.AddMainThreadPass(Pass.BeforeConnections, context => {
NativeArray<bool> nodeWalkable = context.data.nodeWalkable;
NativeArray<uint> nodePenalty = context.data.nodePenalties;
NativeArray<Vector3> nodePositions = context.data.nodePositions;
for (int i = 0; i < nodePositions.Length; i++)
{
// ERROR OCCURS HERE - nodePositions[I] has inaccurate Vector3
Debug.Log($"Rounding {nodePositions[i]} to {nodePositions[i].ToV3IntRound()}");
nodeWalkable[i] = _map.Nodes.NodeDataAtNode[nodePositions[i].ToV3IntRound()].IsWalkable;
nodePenalty[i] = _map.Nodes.NodeDataAtNode[nodePositions[i].ToV3IntRound()].TraversalCost;
}
});
}
}