- Home /
Detect touch on a 2D plane with a transparent image?
I am trying to make a simple jigsaw puzzle where the player can touch and drag a piece. But when the pieces gets close, I need to make sure I detect WHICH piece is touched as they are concave figures.
So a simple boxed approach wont fit once they get dragged near each other.
I was thinking of some sort of masking approach like we used to do back in Flash/C++ days.
Just wondering what great functions we might have available for same thing in Unity?
Any samples/suggestions are welcome. I am trying to figure out if GetPixels is an option or if I should calculate a masking layer from the tranparacy in the PNG or if I can detect the alpha directly and then go through the depth/stacks of objects if the pixel you touch are transparent.
Very interesting. I would use just a box collider, with the size set to approximately 1/3 of the jigsaw piece and centered. Then hopefully none of the box colliders will overlap, but the pieces can only be selected from the center. Or align the box collider on the piece where you think a player would intuitively press/touch to select the piece. This is just a suggestion (and not what you want!), so good luck, and I am upvoting this question =]
Answer by DaveA · Oct 18, 2012 at 11:07 PM
You can use GetPixel and read out the alpha. You'll need to make sure the texture (import) settings allow read/write (even if you are only reading it). If there is only one material on your mesh, no problem. If it is a multi-material (has submeshes), it's a pain to track down which submesh is hit, hence its material. Hope you don't need that.
If you are using rectangular (or not very high-detail) meshes, they will interpenetrate each other. So your raycast should be of the variety that gives you the list of objects hit, not just the nearest one. Using the hit point info from the raycast hit, read the pixel at that location, check alpha. If transparent, try next hit on the list, otherwise you found it.