Reputation: 1978
I have lots of meshes for a 2D project that I place on quads (as a material to the quads). They're like "maps"; filled from the inside but have transparent edges.
I make a polygon collider for each map and place it on top of it so that I can use Physics2D.Raycast()
to detect whether the user has placed an object on the map or off the map. They're like shapes (polygons).
The process of making the polygon collider is time-consuming and the quality isn't so good. Is there some Mesh collider that detects transparency and therefore shapes itself to the shape of the map? Or is there a way to make a script that shapes the collider to the shape of the map?
Upvotes: 2
Views: 1940
Reputation: 1978
Turns out that the Polygon Collider 2D
has got a software feature to generate a polygon to such a transparent mesh. One only needs to drag and drop a sprite on the polygon collider component.
Upvotes: 1
Reputation: 2273
Here is the solution: use RaycastAll to retrieve all the objects hit, then return the closest object such that the alpha value of the pixel is not 0.
private static RaycastHit? RaycastWithTransparency(Ray ray)
{
var res = Physics.RaycastAll(ray, float.MaxValue).ToList().OrderBy(h => h.distance);
foreach (var h in res)
{
var col = h.collider;
Renderer rend = h.transform.GetComponent<Renderer>();
Texture2D tex = rend.material.mainTexture as Texture2D;
var xInTex = (int) (h.textureCoord.x*tex.width);
var yInTex = (int) (h.textureCoord.y*tex.height);
var pix = tex.GetPixel(xInTex, yInTex);
if (pix.a > 0)
{
//Debug.Log("You hit: " + col.name + " position " + h.textureCoord.x + " , " + h.textureCoord.y);
return h;
}
}
return null;
}
Upvotes: 1