Summary: I've been trying to figure out a way to use simple box colliders as a nice and efficient "first pass" collider. For the "second pass", I want to check that the area clicked has an alpha value > 10%. I know this is generally possible with graphics programming, but I'm struggling to find a way to do this in Unity2D with packed sprites (packed via the native Sprite Packer tool).
What I was hoping to do (but Unity will not allow) would've been something like...
// Check to see if a point intersects with a solid color
private bool CheckPoint()
{
Vector2 cursorWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//foreach (Collider2D col2D in Physics2D.OverlapPointAll(cursorWorld))
foreach (RaycastHit2D hit in Physics2D.RaycastAll(cursorWorld, Vector2.zero))
{
if (hit.collider.gameObject != gameObject) continue;
foreach (SpriteRenderer sprRend in hit.collider.gameObject.GetComponentsInChildren<SpriteRenderer>())
{
Texture2D tex = (Texture2D)sprRend.sprite.texture;
// this is the missing link; easy with 3d, but impossible with 2d?
Vector2 pixelUV = hit.??????;
int uvX = (int)(pixelUV.x * tex.width);
int uvY = (int)(pixelUV.y * tex.height);
Color hitColor = tex.GetPixel(uvX, uvY);
if (hitColor.a > 0.1) return true;
}
}
return false;
}
So far: I've been able to find some solutions for doing this with (3D) meshes and 3D colliders. However, the 2D colliders do not include the UV data that would be needed to make this work.
Someone was also able to get this working for their specific game using SpriteManager2 (which we're not using since Unity 4.3 makes SM2 mostly unnecessary) and posted their solution here... http://answers.unity3d.com/questions/17903/detecting-mouseclick-on-pixels-in-sprite-using-sm2.html and I think the same approach might work with minor adaptations for Unity2D, but I'm thinking there might be a more robust approach.
I'm also looking at trying to do something like http://answers.unity3d.com/questions/687116/what-is-the-easiest-way-to-convert-raycasthit2d-to.html but even if I can calculate the local UV, that wont help me with the real UV for the packed sprite unless I can somehow get the sprite's UV offset into the sheet.