I don't quite understand the WillBlockPath method

Okay so:

  1. Why do we set isWalkable to false just to set it back to true after getting a new path?
  2. Actually why do we need to get a new path?
  3. Why do we check the newPath.Count?

I found this lecture to be one of the most difficult to understand in the entire course so far: frowning:

 public bool WillBlockPath(Vector2Int coordinates)
    {
        if(grid.ContainsKey(coordinates))
        {
            bool previousState = grid[coordinates].isWalkable;

            grid[coordinates].isWalkable = false;
            var newPath = GetNewPath();
            grid[coordinates].isWalkable = previousState;

            if(newPath.Count <= 1)
            {
                GetNewPath();
                return true;
            }
        }
        return false;
    }
1 Like

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. :slight_smile:

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? :slight_smile:


See also:

5 Likes

Okay I think I understand it better now. Thank you! You’re very helpful as always :grin:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms