- Home /
Detecting a mouse click on a custom 2D mesh?
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:
1) 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:
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;
}
Answer by Muhwu · Dec 27, 2013 at 07:34 PM
Ok, so I figured out what the problem was. Since the sharedMesh is the same one that is originally set, setting it again doesn't actually update the reference. What I needed to do here was to
mCollider.sharedMesh = null;
mCollider.sharedMesh = mMeshFilter.sharedMesh;
This refreshes it. It looks ugly, so if there is a "correct" way to do it, I'd appreciate getting to know it.
Your answer
Follow this Question
Related Questions
Raycast to align character on MeshCollider normals 1 Answer
Generate mesh from raycast positions, independent of rotations 0 Answers
Get Vertice of a Quad (two tris) via raycast? 0 Answers
Returning list of Triangles, Vertices or Points by raycasting through a mesh (iPhone) 1 Answer
Raycast crashing build on collision with mesh collider 3 Answers