Spent a few days last week getting my Line of Sight code working. I just incorporated it into my Pathfinder class, so that LoS calculations can share the Pathfinder’s unwalkable grid areas. Allow me to go into detail.

One of the best pathfinding articles that I know of is A* Pathfinding for Beginners by Patrick Lester, which I used a reference point to writing my Pathfinder class. If you are looking to write your own pathing system, I highly recommend you give this article a read.

Essentially, A* pathfinding works by storing your world as a grid, setting walls and such as unwalkable areas. A starting path point and an ending path point are set. From there, the path finder traverses the grid. With each grid square check, the distance to the end point are calculated and a weight value is assigned to each adjacent node, taking corner jumping and diagonals into account, while avoided unwalkable areas. When traversal is finished, a low cost path is built based on the grid weight values.

Moving on. Using an enemy searching for a player as an example, my Line of Sight routine requires two tiers of checks, in order.

1. Set up a “Vision Cone”, which is the field of view for the enemy. If the player is in the cone, then…

2. Use a “Line of Sight” check to determine if there is an obstacle between the enemy and the player.

Before, I mentioned that I used my Pathfinder for LoS. What I did is copied my FindPath() method and modified it for my LoS calcs. In LoSCheck, I increased the resolution of the grid (higher memory usage, but more accurate) and check only for obstacle avoidance.

So, my LoS looks to see if there is an unobstructed path from Point A to Point B. If it encounters ANY obstacle, it doesn’t try to path around it, it just returns that Point A could not “see” Point B. It gets the job done and lets me get away with not having to write a whole new system by utilizing something I’ve already written.

Above: Player is in Vision Cone, so a LoS check is executed. Much like a pathfinding check, the green line dictates a successful find. The enemy can easily see the player.

Above: Player is within Vision Cone. The green line shows a normal FindPath() routine, with the ability to detect obstacles and walk around them. The red line is the modified FindPath() (which is now LoSCheck()) that stops at the first detection of an obstacle. We can see that the enemy can’t see the player.

Altogether, I’m pleased with this solution. It runs fast and I didn’t have to reinvent the wheel.