A* with Node Weights and Diagonals

In Example 8-17 we will add back in the diagonal node capability to see whether this will allow for a path that will bypass the grass tiles. A diagonal will add 1.41 (the square root of 2) to the total node path weight, while a grass tile will add 2. For that reason, adding in the use of diagonals will cost less than moving over grass.

//Example 8-17 changes to Example 8-16 to add node weights
var result = astar.search(graph.nodes, start, end, true);

After simply adding true back into astar.search(), Figure 8-17 shows that the grass tiles can be avoided because even though a diagonal adds 1.41 to the path cost, that amount is still less than grass tile movement.

A* with grass tiles and diagonals

Figure 8-17. A* with grass tiles and diagonals

Wow...just adding in diagonal path node capability changed the node structure of the result path dramatically and allowed us to avoid a path that moves over grass tiles. As a final example, and because this book really is about making cool things happen on the canvas, we are going add the green tank from the tile sheet to the demo and have it follow the A* created path.

Example 8-17. Larger A* Example with grass tiles and diagonal movement

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chapter 8 Example 17 - A* with Grass Tiles and Diagonal Moves</title>
<script src="modernizr.js"></script>
<script type='text/javascript' src

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.