MV Smarter pathfinding for chasing events

I feel like this is one that has been done before, but I'm coming up empty on a cursory look through the internet.

I'm looking for a plugin that will essentially make events chasing or following the player smarter. Right now there's a few issues:
-getting stuck on events or tiles
-getting confused and stuck about cliffs, mazes, various walls
-getting confused or stuck if too far away period
-trying to reach the player by simply getting closer to the player, for example on a cliff above the player's position (technically next to the player but on a whole different level of the map), as opposed to taking the ACTUAL route they need to reach the player

I feel like players will complain if my implementation is off so I want it to be as polished as I can. Are there any options available that achieve an intelligent pathfinding?

I'm already using Yanfly's Move Route Core, and it's very useful, but its pathfinding for chasing events is still "dumb." I've also tried Shaz's Smart Pathfinding with the same results.
Pretty much every pathfinding plugin will use A*, and it's also what RPG Maker uses for its findDirectionTo function which is called when you click the screen and the player pathfinds to that tile.

To do the fancy stuff you want taking layers, moving events, etc into account, well, that's something you will likely need to write in extra conditional statements yourself.

It's going to be more complicated and processor intensive than you think, because if the other events are moving it will have to be constantly calculating a new route to go around them, meaning it has to sample every tile in an x tile radius until it hits its target. The longer it takes to find a clear path, or the more often it needs to recalculate, the more lag you'll get.

Play around with this tool and you'll see what's happening when you tell an event to pathfind

The event has to sample all those green tiles to find a path, except now you're adding in extra dynamic walls (moving events) whose position change every frame
1735853345065.png
There is a good one available but for MZ only, can't remember or find
the link to that, but there isn't much perfect path finding like the above
could do, as smart pathfinding to keep everything in mind might be
also very complex thing to build.
@muffinswords I create 2 mini functions for a more cleaner pathfinding.
depending how many events are chasing (just tested with 1 events and
blocked ways, but seems to work nicely (2 scriptcalls, but 1 required).

Spoiler: How to use
Inside moveroute, use the following Scriptcall:

this.chasePlayer()
or
this.chasePlayerVariables(vx, vy)

This scriptcall chase the player and wont block in corners, but find it's way clean and better.
Using variables require a common event and in parallel that tracks the player X and Y on the map
and a switch to activate (use 2-5 wait frames) and it finds the player by variables.
activate the switch whenever required inside the map of chasing.

using the first doesn't require a switch, but if you need variables, it can work out.
this works in both MV and MZ as they are equal so far I see it, so it's really easy
to use plugin, see if it works on your end.

you may change the plugin name, as it doesn't impact anything, so I leave it here 🙂
but I might implement it into my base later on for others to use, so it's a small
function for you 😀
If I recall correctly touch/mouse control does have a pathing finding logic, at some degree.
But the player can be trapped inside a U shape area sometimes.

I wonder if changing search limit will fix the problem (or maybe cause other problems?).

Edit* Tried, it doesn't seem to work.

JavaScript:
Game_Character.prototype.findDirectionTo = function(goalX, goalY) {
    var searchLimit = this.searchLimit();
    var mapWidth = $gameMap.width();
    var nodeList = [];
    var openList = [];
    var closedList = [];
    var start = {};
    var best = start;

    if (this.x === goalX && this.y === goalY) {
        return 0;
    }

    start.parent = null;
    start.x = this.x;
    start.y = this.y;
    start.g = 0;
    start.f = $gameMap.distance(start.x, start.y, goalX, goalY);
    nodeList.push(start);
    openList.push(start.y * mapWidth + start.x);

    while (nodeList.length > 0) {
        var bestIndex = 0;
        for (var i = 0; i < nodeList.length; i++) {
            if (nodeList[i].f < nodeList[bestIndex].f) {
                bestIndex = i;
            }
        }

        var current = nodeList[bestIndex];
        var x1 = current.x;
        var y1 = current.y;
        var pos1 = y1 * mapWidth + x1;
        var g1 = current.g;

        nodeList.splice(bestIndex, 1);
        openList.splice(openList.indexOf(pos1), 1);
        closedList.push(pos1);

        if (current.x === goalX && current.y === goalY) {
            best = current;
            break;
        }

        if (g1 >= searchLimit) {
            continue;
        }

        for (var j = 0; j < 4; j++) {
            var direction = 2 + j * 2;
            var x2 = $gameMap.roundXWithDirection(x1, direction);
            var y2 = $gameMap.roundYWithDirection(y1, direction);
            var pos2 = y2 * mapWidth + x2;

            if (closedList.contains(pos2)) {
                continue;
            }
            if (!this.canPass(x1, y1, direction)) {
                continue;
            }

            var g2 = g1 + 1;
            var index2 = openList.indexOf(pos2);

            if (index2 < 0 || g2 < nodeList[index2].g) {
                var neighbor;
                if (index2 >= 0) {
                    neighbor = nodeList[index2];
                } else {
                    neighbor = {};
                    nodeList.push(neighbor);
                    openList.push(pos2);
                }
                neighbor.parent = current;
                neighbor.x = x2;
                neighbor.y = y2;
                neighbor.g = g2;
                neighbor.f = g2 + $gameMap.distance(x2, y2, goalX, goalY);
                if (!best || neighbor.f - neighbor.g < best.f - best.g) {
                    best = neighbor;
                }
            }
        }
    }

    var node = best;
    while (node.parent && node.parent !== start) {
        node = node.parent;
    }

    var deltaX1 = $gameMap.deltaX(node.x, start.x);
    var deltaY1 = $gameMap.deltaY(node.y, start.y);
    if (deltaY1 > 0) {
        return 2;
    } else if (deltaX1 < 0) {
        return 4;
    } else if (deltaX1 > 0) {
        return 6;
    } else if (deltaY1 < 0) {
        return 8;
    }

    var deltaX2 = this.deltaXFrom(goalX);
    var deltaY2 = this.deltaYFrom(goalY);
    if (Math.abs(deltaX2) > Math.abs(deltaY2)) {
        return deltaX2 > 0 ? 4 : 6;
    } else if (deltaY2 !== 0) {
        return deltaY2 > 0 ? 8 : 2;
    }

    return 0;
};

Game_Character.prototype.searchLimit = function() {
    return 12;
};
just a thought to prevent "trapping". Have the program calculate a larger pattern every 5 to 10 cycles, and if detected, calculate a path out of the pocket zone. This wouldn't prevent it from going back in, but at least it wouldn't get trapped there. The condition for knowing if it is trapped... (X and Y coordinates over time did not change by more than X. This would kick it to long range detection. If the event is actually trapped, it would be no harm, no foul... and use up less resources than a constant check.
just a thought to prevent "trapping". Have the program calculate a larger pattern every 5 to 10 cycles, and if detected, calculate a path out of the pocket zone. This wouldn't prevent it from going back in, but at least it wouldn't get trapped there. The condition for knowing if it is trapped... (X and Y coordinates over time did not change by more than X. This would kick it to long range detection. If the event is actually trapped, it would be no harm, no foul... and use up less resources than a constant check.
I have thought about that but the solution is no better than using a path finding plugin.
Maybe for some zombies it looks good, still looks a bit stupid for a human character.

An alternative method is setting up some waypoints manually on the map. All the waypoints connect to each other. Let both the target and the chaser find their nearest way point so they will have a path to each other. Still this is not as easy as just using A*

Maybe for game that uses pixel movement instead of grid based movement, it has some use.
the way I set it works nice, and is a very short snippet to use both.
it might not work when the event is outside range, (or map) but
you there are plugins that update outside the map, and the range
has to be evented to avoid problems.

so player.x and player.y can be in a conditional branch for a range
of 5 or 10 or whatever.

maybe even coded in.

it's just a shame that smart path finding doesn't work correctly, but with
the 2 simple calls I made does work far better than the smart path finding 🙂

at least event to player that is or event to variable x,y.
When a character is pathfinding (e.g. the player via touch input) the core engine calls findDirectionTo every step, which uses an A* algorithm to (re)find a path, up to the search limit, and returns the direction for the next step along that path. Yanfly's and Shaz's plugins simply use this built-in pathfinding, because why not?

Well, the default search limit of 12 tiles is tuned to the standard 17x13 tiles per screen, since it's only designed for player touch movement. That does mean it will fail over larger distances for certain configurations of obstacles. As you can see from the link/screenshot AquaEcho shared, the impact of increasing the search limit is very dependent on the map layout: narrow corridors will cause minimal issues, while open-plan maps will be much more CPU-hungry.

In terms of failure: A* with no search limit is mathematically guaranteed to find a path if one exists. So if effectively removing the search limit (e.g. 9999, or Infinity) does not help, it's something else (or there is a 9-year-old flaw in findDirectionTo). Ideas:
  1. If it locks up completely with a high search limit then try turning off any plugins you're using in the Plugin Manager (right-click -> Turn OFF) to see if that helps. E.g. a plugin that adds mechanical map layers may change the passability of a tile based on the character's current layer: findDirectionTo doesn't account for layers by default, so that plugin (or an extension for it) would have to patch the pathfinder appropriately to avoid related bugs. Bugs like, say, pathing from tile A (lower layer) to tile B (upper layer) when the target XY is only accessible on the lower layer: the path returns to A, but then is back where it started - a loop.

  2. If it results in pathing that stops unexpectedly (or never!), and/or does a lot of moving back and forth, that may be due to passability changes during the movement. If, say, a shortcut is periodically opening and closing, the pathfinder might alternate between "let's take the shortcut" and "looks like we have to go the long way around". A similar thing can happen with a wandering NPC temporarily blocking a hallway.

    Accounting for changes over time means that you basically have to "path" in some way for all agents in the area just to move one of them, e.g. LPA* or (more practically) D* Lite.
An alternative method is setting up some waypoints manually on the map. All the waypoints connect to each other. Let both the target and the chaser find their nearest way point so they will have a path to each other. Still this is not as easy as just using A*
I wrote a script that makes a character move to the closest tile of region X so I guess you could do it that way.

Original thread: https://forums.rpgmakerweb.com/threads/smarter-pathfinding-for-chasing-events.174229/