Scan if unit is visible to an other unit

In my 2D game, the stage is an 2d char array.The values of the array is either 0, for solid(wall), or 1, for hollow.
So if unit stands on x:150 y:200, I want to check if he can “see” an other unit that stands on for example x: 450 y:300.
By “see” I mean there is not a wall(solid space) between them.

Any tips?

Try a line algorithm, like Bresenhams, or just this:

Check if no square on the line is blocked. Then the units can see each other. Some line algorithms are unsymmetric, in that case you need to check both directions (lines from->to and to->from)

There are several examples of how to do this on: http://roguebasin.roguelikedevelopment.org/index.php?title=Field_of_Vision

You can use this code to check if a wall is in a units line of sight.


Unit u = ...;
Vec2 direction = new Vec2(1, 0); // whatever direction the unit is facing, 1,0 = along the X axis
Vec2 searchPosition = u.position().clone();
for(int i = 0; i < u.searchDistance /* how far should we cast a ray*/; i++) {
     if(map[searchPosition.x][searchPosition.y] == 0) {
         return true;
     }
     searchPosition.add(direction);
}
return false;

If a wall is in the way this code will return true, if not it will return the opposite. With a few modifications you can make it check for another unit.

Bresenhams is not really appropriate since it may jump over solid cells or around corners. A specific visibility algorithm (like the ones saifix linked to) give much better results.

I ended up adapting the Wolf3d cell scanning algorithm.

Thanks for the code saifix. I will try to understand the code instead of just copy and paste.
Could you please give a more detailed explanation of the code? For instance, what is Vec2? The arg to direction, is that X Y coordinates to an object?

Also, your code just check a straight line, right?

Vec2 is a vector made up of 2 components, x & y. The arguments are the direction which the casted ray is traveling in, if it were (-1, 0) it’d test a straight line starting going to the left of the unit and if it were (0, 1) it’d test a line traveling up from the unit.

Yes, it only checks a straight line.