Hi Taachii,
Thank you for your questions. Admittedly, pathfinding algorithms can be fairly complex but they are very important for game developers, so it is always good to know at least one of them. Don’t worry if you do not understand everything at the first onset.
Actually why do we need to get a new path?
Imagine your enemy has got a path from the start to the goal. If you place a tower on said path, the current path is blocked because the enemy is not supposed to walk through the tower.
To make our game continue, we have to calculate a new path for the enemy. However, we are no clairvoyants, thus we do not know if there is an alternative path. That’s what we need to figure out before instantiating the tower. And we do that in the WillBlockPath method.
If there is no alternative path, we must not instantiate the tower at that position.
Why do we set isWalkable to false just to set it back to true after getting a new path?
Before we instantiate the tower, we think about “what would happen if we instantiated the tower?”. The tower itself is irrelevant for our path and pathfinding algorithm. What matters is the value of isWalkable
. When we place a tower on a waypoint/tile, that waypoint becomes “not walkable”. We would set isWalkabe
to false
in that case.
And that’s what we do here. We calculate the path with the new grid data where the waypoint on which we plan to instantiate the tower is “not walkable”.
Why do we check the newPath.Count?
GetNewPath returns an alternative path. If that path consists of 0 or 1 waypoint(s), there obviously is no path. At least, that’s Gary’s definition of “no path”.
Did this clear it up for you?
See also: