Specific 2D movement using Dijkstras Algorithm...

Hi,

I’m playing around with a top down 2D game and i’ve reached a point where I need to implement some kind of pathfinding.
I followed a great tutorial for Dijkstra’s Algorithm and i’ve got my character moving, but not exactly the way I’d like.

Here’s my characters movement code: PirateAI.

The way it works is while most of the nodes on my ship are empty game objects, some of them are clickable, visible objects. Clicking on one of the visible nodes assigns its gameObject to the target variable in the above script and the selected character moves towards it.
This is working. However three things are happening that i’d like to change/stop.

First of all the character is able to move diagonally. Is there a way to discourage diagonal movement so the character only moves vertically and horizontally?

Second, the character stops a short distance from the target node instead of directly on top of it. Is there a way to make sure my character stops at the nodes exact position?

Finally when the character stops moving I’m getting the following error over and over: “InvalidOperationException: Operation is not valid due to the current state of the object”
Its saying its happening on line 7 of the above linked code.

Anyone have any ideas?

The other scripts used are here: DijkstrasAlgorthim, CurrentNode, Node

Pirate is red, target is green.
How do you want the pirate to walk? And what is your tilesize?

Walk Styles

  • For blue, check if x-Distance or y-Distance is shorter and walk that first and then the other axis. If you use a Coroutine, you don’t need to keep track of what you decided between frames.
  • For yellow alternate the axes if there is still some distance left on the axis.
  • For red, walk the longer axis till both axis are the same, then same as yellow

Let me know if you need more help