I’m trying to create my first 2D RPG game and am running into an issue with pathfinding. I’m using LibGDX framework and imported this pathfinding into my project
It works well when dealing with non diagonals (although it wall hugs), but when adding diagonal’s it makes really questionable and noticeable movements which can kill immersion.
I’ve posted a picture of the pathfinding, this is the code that I changed to add diagonal’s.
The old code
for (int x = 0; x < sizeX; x++) {
for (int y = 0; y < sizeY; y++) {
nodes.add(new FlatTiledNode(x, y, map[x][y], weight[x][y], 7));
}
}
// Each node has up to 4 neighbors, therefore no diagonal movement is possible
for (int x = 0; x < sizeX; x++) {
int idx = x * sizeY;
for (int y = 0; y < sizeY; y++) {
FlatTiledNode n = nodes.get(idx + y);
if (x > 0)
addConnection(n, -1, 0);
if (y > 0)
addConnection(n, 0, -1);
if (x < sizeX - 1)
addConnection(n, 1, 0);
if (y < sizeY - 1)
addConnection(n, 0, 1);
}
The new code
// Each node has up to 4 neighbors, therefore no diagonal movement is possible
for (int x = 0; x < sizeX; x++) {
int idx = x * sizeY;
for (int y = 0; y < sizeY; y++) {
FlatTiledNode n = nodes.get(idx + y);
if (x > 0)
addConnection(n, -1, 0);
if (y > 0)
addConnection(n, 0, -1);
if (x < sizeX - 1)
addConnection(n, 1, 0);
if (y < sizeY - 1)
addConnection(n, 0, 1);
if (x > 0 && y < sizeY - 1) {
addConnection(n, -1, 1);
}
if (x < sizeX - 1 && y > 0) {
addConnection(n, 1, -1);
}
if (x < sizeX - 1 && y < sizeY - 1) {
addConnection(n, 1, 1);
}
}
}
Changing the heuristics to octile didn’t make any difference either
public float estimate (N node, N endNode) {
float F = (float) (Math.sqrt(2) - 1);
int dx = Math.abs(endNode.x - node.x);
int dy = Math.abs(endNode.y - node.y);
return ((dx < dy) ? F * dx + dy : F * dy + dx);
}
Any help would really be appreciated.