I have a 2D game core where I create trails using custom meshes. I want to be able to detect a click on this customly created mesh. I tried adding a MeshCollider and used an example code I found:
if(Input.GetMouseButtonDown(0))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit))
Debug.Log("Mouse Down Hit the following object: " + hit.collider.name);
else
Debug.Log ("Nothing was hit!");
}
It seems to “sort of work”. I get an occasional hit from this, but the result seems really random.
Basically all I need is to see if my trail has been clicked, but at this point I’d be happy to get some insight into how I can visualize the shape the raycaster tests against.
[Update] Ok, so I found 2 issues with this:
-
The normals were only correct for half the triangles. I changed the generation algorithm so now the normals are faced towards the camera. However, now it only works for the 1st quad being drawn which takes me to issue 2:
-
The mesh collider isn’t being updated despite me calling mCollider.sharedMesh = mMesh; at the end of the update. I can update it manually by clicking any of the variables in the editor, such as IsConvex to on and off and it works splendidly after that. How do I do this refresh manually through code? This is my currect mesh construction code:
void ConstructMesh()
{
mMesh.Clear();mMesh.vertices = vertices; mMesh.normals = normals; mMesh.triangles = triangles; mMesh.uv = uvs; mMesh.RecalculateNormals(); mMesh.RecalculateBounds(); mMesh.Optimize (); mCollider.sharedMesh = mMeshFilter.sharedMesh;
}