- Home /
Collision with light
Trying to create a 2d stealth game where the enemy uses light to show their view range and if the player touches the light, they are detected.
Normally I would use a collider that will follow the enemy around as a mean to create effective range, but the problem this time is since it is light, the view range changes when the enemy is looking at an obstacle, say a wall. The wall blocks off the light, and so if the player is behind a wall, the enemy should not be able to see them, there fore the collider needs to be shorten to match the size of the light.
I was thinking about using raycasting of three directions (above, below, and forward) to check if the ray hits the player first. I feel like this way the player can slip through the rays even if they are in range of the light sometimes.
Is there a good way to do this or is it a hassle no matter what?
Answer by fafase · Jun 21, 2015 at 05:01 PM
Since you are in 2D, you should use a triangle of linecast. One goes from light position and upwards , one from light position and downwards and one joining the end of both.
See on the drawing below, the two line cast leaving from the light and the one perpendicular.
This way, there is little to no chance a character can be inside without hitting one of the cast first.
Bets is that you place two game objects in front of the player that you parent so they move with him, and you use those to start/end the line cast.
Really clever, but I have a few problems about this solution.
In figure one, E (enemy) have the view of the yellow triangle, but the light is only the green part. P (player) is inside the triangle, so even though he is not inside the light, the enemy still detected him.
Of course, from the up and down ray, I know the player is not the first collider hit and so the player can be behind a wall.
But if the same solution applies, there will be another problem in figure two where the up and down ray is the one hitting walls while the third ray is not.
Quick way I can think of, if one of the linecast hits the player draw a linecast between the enemey and the player position. If that one succeeds then your player is within light and the enemy sees him.
This extra check is only if one of the linecast succeeds.
Your answer
![](https://koobas.hobune.stream/wayback/20220613201234im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity2D side collision detection 1 Answer
How to change the color of the ball after hitting square? 5 Answers
Collision on specific Frames 1 Answer
Why does my OnCollisionEnter2D not work? 3 Answers
Unity2D Collision is bugged 0 Answers