Hi guys,
There has been a few posts on this but none of the solutions offered work for me. When i try measuring the collision depth by casting a ray from the contact point outwards (away from the center of the object)
-Unity misses my object and the colliding object
-Unity picks an object outside and when i try to reverse that raycast unity actually collides with the contact point i gave for the first collision (See image).
The answer above is how we do it in The Other Brothers. The ray cast begins from the center of the character and casts down. This is because raycasts are 1 way, and ignore the object it is already penetrating (if convex - concave or soups may stll pick it up). Use common sense to solve it.
Use 2 game object positions and Physics.Linecast instead if you need to visualize it (use Debug.Drawline as well).
int layer = 1 << 8; //i set my object to user layer 8
//Position is the exact same as my bounds.center
Vector3 rayNormal = (contactPoint - this.position).normalized;
The function only returns true if it hits the same side of a plane from which the plane’s normal emerges. If a plane is flat on the XZ axis, the ray must originate from above Y=0 in order to have a chance of detecting the plane.
All convex objects have all their plane normals facing away from the object’s center to some degree, so no convex shape can be detected by a raycast from its interior.
A concave object may be detected if the ray goes through an empty space in the object before reentering it.
You can’t disable or change this because this is how raycasts work. If it did something different it wouldn’t be a raycast anymore
You can create a sphere yourself in a modeling program and include inward-facing planes (and then use mesh collider instead of sphere collider), and you’ll be able to detect the sphere with raycasts from its interior.
If that is the case then why does raycast 2 fail? It is coming from outside in.
I really think i must be doing something terribly wrong that i cant see (blaming the wrong code).
I might just have to use cubes or cylinders for my collider
or replace capsules with continuous swept spheres ever step (stupid expensive i presume).
IF this is a bug, I’d guess that the raycast function is incorrectly counting the sphere’s wrong-way-faced polygons when it’s casting “up” in your image above. A simple way to raycast is just to count the number of planes you pass; when you hit an odd-numbered plane then it counts as a collision, so it might see first the cube’s bottom edge and then its top edge as the odd-numbered collisions.
If it’s not a bug, it seems quite possible to me that objects just don’t penetrate each other long enough for code to detect it. I’ve never worked with penetration depth; my first guess would be that the physics solution would penetrate the objects, realize they’ve penetrated, and move them back to non-penetrating positions before returning code flow to the user.