How to convert Mesh to Sprite in Unity

Viewed 1142

I am making a 2D stealth game. The player has a view cone that shows the players lines of sight. Currently the view cone is a mesh rendered infront of 2D sprites in a 2D game. I am trying to use a sprite mask to hide enemies when they are not in the players line of sight.

I tried using a sprite mask for this but the sprite mask component requires a sprite while I have a mesh. Sprite Mask Component

I want the red square to only be visible while behind the yellow fov cone.

The fov mesh is calculated at runtime with raycasts and constructed from the hit points of those casts.

Is there a way to convert the mesh into a sprite to use with a sprite mask?

Game

1 Answers

I don't know why you're starting with 3D objects (I assume 3D because you used the word "cone"), if all you want is 2D. This is what 2D spotlights are for -- why not let the 2D lighting system do this kind of work, and then detect if it's in the range of the spotlight by using 2D raycasting? It seems like you must have started working with 3D, but you should start over again in 2D, and save yourself a lot of wrangling, if you want this effect. Otherwise you'll always be fighting the 3D meshes to get 2D effects.

But if you must use a 3D mesh, then leo Quint's comment is right. I've seen people do things like this with rain drop effects in 2D games. Another, simpler way to do it would be to have the red square's renderer only turn on when it collides with the yellow mesh...

UPDATED 7/14 FOR MORE DETAILS:

I don't have an example, but I don't think it needs to be complicated. You use the 2D raycasting code here:

https://docs.unity3d.com/ScriptReference/Physics2D.RaycastAll.html

And you check all the objects it hits, to see if they're something you'd like to appear in the light. If it is, then you turn that object's renderer on. I'm sure you can think of some effect that's better than the object just blinking on.

2D spotlights have an angle width, and you can check if any point in the lightable object is within a certain number of degrees (and within the radius) of the thing that needs to light things up. Think of a clock. Let's say your character is in the middle of the clock, looking at the 3, and the enemy is at the 6. As your character turns towards the 6, gradually it comes within the range of the thing that needs to be lit up.

Related