- Home /
Raycasting not working on a procedural mesh with a mesh collider.
I wrote some code that creates a procedural mesh made out of smaller cubes, its basically the same as the code on this video only it supports 3 dimensions (X,Y,Z):
https://www.youtube.com/watch?v=bFKgiPomYpM
The problem is that it does not detect the mesh collider when ever a ray is cast at it, it just goes trough as if nothing was there.
Here is the code used for the collision detection:
private void Update(){
UpdateVoxelMesh(data);
UpdateMesh();
//Rayrace to get the click position
if (Input.GetMouseButtonDown(0)){
Vector3 clickPosition = -Vector3.one;
Plane plane = new Plane(Vector3.up,0f);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distanceToPlane;
if (plane.Raycast (ray, out distanceToPlane)){
clickPosition = ray.GetPoint (distanceToPlane);
}
print(clickPosition);
}
Some Images:
Your mesh collider doesn't have a mesh associated with it. Assign the same mesh as in the mesh filter component. If you remove and then re-add the $$anonymous$$esh Collider component then it should do this automatically.
I have the same problem... procedural mesh.... except $$anonymous$$e has been working for a few years... updated Unity to 2019.1 now it doesn't work anymore. I have the mesh collider assigned. Unity physics collides with the mesh, but ray-cast does not work anymore. The layering is correct, nothing else changed. I tried setting the collision mesh to null, right before re-assigning it again. doesn't work.
I see there are new options to do with "$$anonymous$$eshColliderCookingOptions" on the component now... but they don't seem to fix things....
Answer by BBIT-SOLUTIONS · May 02, 2020 at 01:25 AM
Some ideas, maybe one of them could help you:
Try setting convex on your Mesh Collider
Try using a BoxCollider instead of the MeshCollider
Instead of using ScreenPointToRay() you could try using ViewportPointToRay()
Use a Physics.Raycast instead of the Camera.main.raycast
Your answer
Follow this Question
Related Questions
How do i get local Hit position of Raycast on a collider 1 Answer
How can I let the ray to the edge of the capsule? 1 Answer
Weird bounce on collision with perfectly aligned (generated) meshes for fast object 3 Answers
RayCast2D problems on collision detection 3 Answers
Raycast not hitting collider 2 Answers