Home > front end >  Dijkstra pathfinding algorithm always returning empty paths to tiles in 2d tile-based game I'm
Dijkstra pathfinding algorithm always returning empty paths to tiles in 2d tile-based game I'm

Time:11-13

I'm coding a 2d tile-based, turn-based game in Unity, and have been struggling to solve a problem for the past two days. At first, I managed to get tile to tile pathfinding working using the Dijkstra algorithm. Next, I tried modifying the code to instead efficiently pathfind to every tile within a character’s movement range

To that end, I’m trying to make a method that returns a dictionary. The keys are all the reachable WorldTile tiles within the character’s mobility range (WorldTile is a class representing each tile in the game) and the value for each key is a PathAndCost pathAndCost (PathAndCost is a class that stores 2 properties: Path, of type Queue and Cost, of type Double).

This way, I can store a list of all the tiles the character can reach while simultaneously also storing the path to each tile (represented by a Queue of tiles) and the cost to reach each tile (represented by a Double).

However, in practice, there is something wrong with the method and I can’t figure out what exactly is wrong. Through testing, I’ve confirmed that the dictionary that the method returns DOES correctly contain all the reachable tiles as its keys. Meanwhile, the pathAndCost values returned are only half correct. Strangely, each pathAndCost.Cost is correct. However, pathAndCost.Path is always wrong. When I check the queue count of the paths being stored, it’s always 0, meaning no tiles are stored in the paths!

github link to my script

(apologies if formatting of my post or code is messy as I am new to both stackoverflow and programming)

If you look at the two Debugging blocks I wrote in my script, INSIDE the StorePathAndCost loop, the paths are indeed being made correctly as queue counts there are not always 0. Somehow, something goes wrong afterwards that sets the paths back to being empty before the method returns the dictionary.

Since the tile keys and cost values aren’t being affected, I highly suspect that there is a logical error in the way I’m making and storing the paths within the StorePathAndCost loop. I’ve stared at my code for so long and can’t figure out what it is though.

EDIT: Solved! Realised that the problem lies in the Dequeue() method affecting my path values even after they were stored in the dictionary.

CodePudding user response:

Not going to wade through your whole program code, but I will offer help in the form a nice video tutorial showing a successful way of implementing pathfinding for ya.

Tarodevs Pathfinding

  • Related