- Home /
Unity 2D: query for "mask/layer" bit on screen space without collider
Hi all, I'm currently working on a 2D game.
I have a bunch of sprites (currently with only black or transparent areas) displayed on the screen and I would like to know if an user input (actually is an input touch but could also be a mouse click) is in the black area of my sprite.
The touch input comes in screen coordinates so I had in mind to do something like this:
Receive the user input at the screen point X
Look at what is displayed by the main camera at the point X, in a certain layer (I need to query only to these kind of sprites)
If the alpha (or the color) of that corresponding point is 0 -> do semething, else -> do other things
I can get the world coordinates of the point with the ScreenToWorldPoint()
method but I don't know how to get some data associated to the sprite in that position. I need some sort of binary mask of the screen (like a 0-1 accessible camera depth buffer or idk).
I would like to avoid using colliders because the sprites could be somewhat irregular as this:
and i need to be accurate with the checks. The code will be placed in the Update()
method so it can't be too much burdensome to be processed.
Any idea or place to be pointed to?
Thanks in advance
Answer by MarcoComolli · Dec 16, 2017 at 07:23 PM
It took me a bit but I've found a solution, maybe not the optimal one or the most elegant but for me it works.
For any other interested I've used one RenderTexture
with these steps:
Create a RenderTexture (for my checks I use a 32x32 texture, don't use a big texture resolution in the update cycle or the performances reduce drastically)
Create a secondary camera with culling mask to the selected layer (the one with the mask sprites)
Select the texture as the camera target texture (adjust camera setting to render only a portion of 32x32 pixel of screen >>> check the orthographic size for this).
Make a script to place the camera where the touch input arrive
Create a texture2D from the RenderTexture to access the mid pixel of the new texture generated
The cons is that actually (if I'm not mistaken) the accessed pixel is 1 frame later compared to the actual update cycle because of the camera OnPostRender()
method, but 1 frame is quite irrelevant in my case.
Hope it helps.