Dungeon Crawler LoS

closed account (D3pGNwbp)
Anybody know an efficient way to do line of sight for an ASCII dungeon crawler? I have a couple ideas in my head; but, they're probably not the best. Just would like to know how other people would go about doing it. Thanks.

Edit: like the line of sight shown here http://i.imgur.com/CTctB.png
Last edited on
Conceptually it's pretty simple:

1) Create a line originating from each surrounding tile (such as tiles within X distance of the player) to the player's tile.

2) Check each tile that the created line overlaps.

3) If any of the checked tiles are walls, the original tile is not in the player's line of sight.


The only part that's somewhat tricky is the algorithm for step #2. It's a common problem so there's probably a bazillion algorithms available if you want to google them (but I don't know the specific name of the problem so I'm too lazy to do it myself).

One way to do it that's pretty easy is to create a unit vector and step in increments of 1 'tile' along that vector until you exhaust the entire length of the line. That may not make a lot of sense to read, so here's some pseudo code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool LineOfSight( int playerx, int playery, int targetx, int targety )
{
    double x = targetx - playerx;  // EDIT - fixed these two lines, had them backwards
    double y = targety - playery;
    double len = std::sqrt( (x*x) + (y*y) );

    if(!len)  // player tile is same as target tile
        return true;

    double unitx = x / len;
    double unity = y / len;

    x = playerx;
    y = playery;
    for( double i = 1; i < len; i += 1 )
    {
        if( isTileAWall( (int)x, (int)y ) )
            return false;

        x += unitx; 
        y += unity;
    }

    // didn't hit any walls
    return true;
}




EDIT:

Although with the sqrt call and the possibility for checking the same tile multiple times... that probably makes this not the most efficient method. It's just the first one I thought of.


But if you're doing an ASCII dungeon crawler I highly doubt efficiency is much of an issue.
Last edited on
closed account (D3pGNwbp)
Thankyou! Looks great, not really as complicated as I thought it would be; that's good, lol. Can't wait to work it in.
NP. Just edited with a correction.
Topic archived. No new replies allowed.