# How can I create 2D shadows that let me detect when the player is inside them?

I'm working on a 2D platform game, and I want my platforms to cast shadows along with some way to detect if the player is inside the shadow area (that is, not hit by the sun).

More specifically: I have a character, some platforms and a sun. When the player is under the shadow of some platform he is safe. If he goes to a location when the sunlight hit him, then he starts losing heath until he enters other shadow spot.

Right now the shadows are boxes with a transparent/diffuse material. Boxes are good because I can determine when the player enters or leaves them, but they are are ugly and don't have any animation. I need a shadow that changes when the sun changes its position, without losing the ability to determine when the player is inside a shadow (I think this can be done using a ray cast)?

How can I accomplish this?

• Look into procedural meshes(specifically planes). There are plenty of 2D shadow tutorials online, you just need to figure out how to integrate it into a procedural mesh.
– Grey
Commented Jan 13, 2014 at 21:41
• forums.tigsource.com/index.php?topic=8803.0 Commented Jan 15, 2014 at 5:41

I did a quick sketch of how it could be done.

Yellow round thing is the Sun, obviously, grey things are rays and black ones are boxes. The blue lines are the shadow triangles and yellow dots are the vertex points.

You cast rays down from the Sun to the edges of the blocks and through them. Take the vertices where it hit the box and the ground. Then you draw the mesh in code.

• what do you mean by "Take the vertices where it hit the box and the ground. Then you draw the mesh in code." how do you perform the actual intersection test ? what if the character was in air yet still partially in shadow? Commented Jan 15, 2014 at 9:59
• The diagram is a good start, but this answer would be considerably improved with more explanation, pseudocode or math. Some discussion of potential edge cases would be nice as well.
– user1430
Commented Jan 15, 2014 at 18:04
• What you mean with "blue line are shadow triangles"? Commented Jan 17, 2014 at 0:43
• @concept3d Intersection test can be done using Physics.Raycast. About "what if the character was in air..." a convention can be made; if the player is partially in shadow it can be decided that he will take damage, don't take damage or take a percent of the damage. Commented Jan 17, 2014 at 2:30
• @agarwaen Yes. You draw that shadow dynamically every frame by making a procedural mesh. Yellow dots are the vertices and blue lines how they connect to form a solid mesh.
– Esa
Commented Jan 17, 2014 at 6:49