Thursday, November 1, 2018

Simulating "line of sight" with obstacles on 2d grid?


Ran into an interesting problem. I need to figure out how to simulate line of sight - simple enough, just on a 2d grid with obstacles. Either a grid cell is visible, or it's not.


I can get something really rudimentary going - like spreading n spaces from player, or blocking horizontal propagation when an adjacent obstacle is detected, but I can't let myself live with it. Plenty of other apps are using more sophisticated methods that slope the line of sight around corners etc, and I want to be up to par.


So far DCSS has been my source of inspiration when I'm stumped, I'm hoping to get something close to what they have: http://crawl.s-z.org/.


Any insight would be appreciated - thanks for the help!


(Forgive if this is embarassingly noobish - only started game dev a few weeks ago, trying hard to catch up.)



Answer



Ray casting is a very fast and efficient way to determine line-of-sight. It basically involves sending a ray (think of it like an infinite laser that can't be redirected) from a certain position in a certain direction. Using this ray, you can determine things like which point(s) it intersects and how far away from the origin it was when it crossed a certain point.


So for example, in a player/enemy scenario, the ray could originate from the enemy with the direction being the location of the player. If the ray collides with a solid tile, the enemy can't see the player. If it doesn't, the enemy can see the player.



Here is an excellent tutorial that will should help.


You can also consider Bresenham's line algorithm (summed up, it creates lines) for something that might be more easily scaled to tiles.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...