How To Implement A* Pathfinding with Swift

Learn how to implement the A* pathfinding algorithm into a Sprite Kit game to calculate paths between two points. By Gabriel Hauber.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

A challenge

How would you give the cat automatic dog-avoidance behaviour? Rather than having to manually navigate the cat around a dog to get to a bone, what could you do to have the cat automatically choose the dog-free route if one is available?

[spoiler title="Avoid Dogs"]
You can't make a tile containing a dog an "unwalkable" tile because then the cat couldn't navigate the maze! Instead, you can increase the cost of visiting a tile containing a dog.

For example, you could say that moving to a tile with a dog in it costs 10 times as much as moving to an empty tile. i.e.:

func costToMoveFromTileCoord(fromTileCoord: TileCoord, toAdjacentTileCoord toTileCoord: TileCoord) -> Int {
  let baseCost = (fromTileCoord.col != toTileCoord.col) &&
                 (fromTileCoord.row != toTileCoord.row) ? 14 : 10
  return baseCost * (gameScene.isDogAtTileCoord(toTileCoord) ? 10 : 1)
}

[/spoiler]

Where to Go From Here?

Download the final project with all of the code from the tutorial (including diagonal movements and dog avoidance behaviour).

Congratulations, you now know the basics of the A* algorithm and how to implement it! You should be able to:

  • Implement the A* algorithm in your own game
  • Refine it as necessary (by allowing different kind of terrain, better heuristics, etc...) and optimize it

A great place to go to for more information on the A* algorithm is Amit’s A* Pages.

If you have any questions or comments about this tutorial, please join the forum discussion below!

Gabriel Hauber

Contributors

Gabriel Hauber

Author

Over 300 content creators. Join our team.