2009/10/22

Line of Sight

While working on my game, I decided that I will at some point want to have line of sight for a unit. This is how I did it.

The game is on a hexagonal grid, so to make it easier, I decided that a circle around the outside of a hex is the size of whatever blocks vision. All I had to do was check each hex to see if it blocks vision, then for each of those hexes, mark all the ones behind them as invisible. What I was left with was a problem like this:



The unit is at A, the hex at B blocks vision, and everything further away than B that is between the yellow and red lines is invisible. So all I had to do was find the equations for the two lines. They turn out to be really elegant. After many pages of math where I made mistakes and relearned algebra, I found the two equations and plugged them into my map editor for testing. Anyone want to give it a try? I'll post the answer in the comments.

Here are the results!

A Small, Simple Map with a blocking hex and a unit:



Showing the LOS:



Yay it works. Here's a bigger example. This is supposed to be a cave interior, so the black is wall, the red is lava and the rest is just ground. The selected unit is in the middle.

Without LOS:



With LOS:

5 comments:

Michael said...

The Yellow Line is :

y = m(x - Ax) + Ay

The Red Line is :

y = n(x - Ax) + Ay

Now for the slopes:

m =
[d(By - Ay) + r(Bx - Ax)] /
[d(Bx - Ax) - r(By - Ay)]

n =
[d(By - Ay) - r(Bx - Ax)] /
[d(Bx - Ax) + r(By - Ay)]

Joe said...

Are you considering a block obscured if it is obscured at all? What if only a small portion of the block is obscured?

Michael said...

I consider the obscured block visible (since you can see walls) but I will have a separate option for terrain types for whether or not they obscure their contents (like a shield or forest) while being visible itself.

Michael said...

wow ok I just got what you meant Joe. I consider a hex obscured if the center point is obscured. In other words, if you can see the center, you can see the whole thing. There may be a better way to do it, but for now it will serve.

Joe said...

Haha,

I was busy trying to figure out how your reply applied to my question.

I'm still stumped on how to figure out the equations here for those lines damn it.