I'm working on the code design/layout/architecture/whatever for a game I'm making. I want to implement line of sight so that things the player can't see won't be drawn on the screen. I found an example that is pretty much what I want. It uses ray casting and I haven't been able to find much on the subject outside of using it in 3D to render a scene.
I have some ideas on the matter that I'll share and maybe I'm on the right path already. If anyone could help me out by explaining it or showing me a good tutorial or some such I would appreciate it.
My world is pretty empty as far as most games go. Essentially, the player is flying around a ship in space and there are asteroid type objects in space. These are the only objects that block line of sight so far, everything else can be seen through.
An asteroid is a simple polygon consisting of points and the lines those points make.
My first thought, which I'm sure is terrible, was iterating along a vector in a loop and seeing what it hit. I won't be doing that lol.
My second thought a few seconds later was to test against the points and lines of the asteroid objects. I would determine open fields of view by testing the points of the asteroid objects and seeing where they intercepted lines of other asteroids. I would create a line function by going from the player's origin of view, the center of the screen, and going to the point in question. Then, using the formula for that line, test it against lines of asteroid objects (after running some yet to be determined algorithm to occlude asteroids that aren't even in the direction the ray is going). This will find the point of intersection between the ray and the line being tested again. I would then take the x value of the point and put it into the formula for the line being tested. If the resulting y value is between the y values of each endpoint of the line segment, then I would know that the ray is intersecting that line and that line is going to block line of sight all the way from one end point to the other end point. This would give me fields to test and see if enemies are within and if so draw them.
I also plan to use this same algorithm for AI navigation. Each area is created procedural during the game, so using navigation nodes is out of the question. I would use this same algorithm for determining areas that are safe to fly in if the AI were to travel in a straight line and whether or not the AI could see the player so they could shoot at them.
Is this a smart way to go about casting the rays? I've got a number of ideas for simplifying the algorithm as a whole (for instance checking if there is even an enemy on the screen to see if it should even determine player LOS and what not), but its the actual testing of the rays themselves and seeing what they hit that I want to make sure I'm on the right track for. It seems like it would be pretty darn fast to me, but my inexperience might hide something from me.