-
Notifications
You must be signed in to change notification settings - Fork 0
Experiment 1 Raycasting Shadows
You might have seen this effect already if you have played many stealth games. It's a command mechanic to mimic line of sight of player/enemy to give games a more realistic stealth feel. This is the effect in action.
The white light you see here is not actually a light but rather a mesh generated at run-time and which changes it's shape according to object's surroundings! No lights were used during the process :)
Basically, raycasts. If you are not sure what raycasting is, it is a good time to look up Unity docs. Surroundings are perceived by firing many rays throughout 360deg. This gives you something like this-
The current setup uses about 180 rays, so that's 1 ray every 2 degrees. Max range of ray is set to 10, so if a ray does not hit any object before that it stops at distance of 10.
The next step is to create mesh out of these end points. Mesh is generated at run-time and updated every frame. This is something called procedural mesh generation. If you are not sure what this is, it's again a good time to look up Unity manual for an excellent introduction to procedural mesh generation.
The origin of the rays is taken as vertex[0] and all the end points in vertex[1..total]. Then we have the following triangles in our mesh -> 0-1-2, 0-2-3, 0-3-4, .... , 0-(total-1)-total, 0-total-1 Putting everything together, this is what we get -
We are done ... in an easy way. In principle, this would work. But! this is an highly inefficient approach. First, look at the poly count of mesh, it's high for no reason. Second, if you actually try this you would notice that the effect does not feel 'natural' when you try to move around. You observe wiggles and strange glitches. This is because apparently 180 rays do not give enough resolving power to properly resolve edges with accuracy enough to prevent shaking. To create more realistic and stable mesh, you would have to increase the ray count to as high as 1000 at least to get somewhere near playable. Increasing ray count to 1000 though means a great deal of performance hit. Not only firing 1000 rays is CPU intensive, generating a mesh with as many vertices EVERY FRAME is also a significant performance hit. To keep high performance we need to achieve the same effect as in 1000 rays with as little rays as possible. Thus, there is a need to optimize the process.
The current algorithm uses 2 simple techniques to achieve this optimization - Batching and iterative optimization. Discussed in next article.