- Home /
Using the UnityEngine.Plane struct, what's the best way to check if a collider is crossing said plane?
The function I was hopping for was something that like this:
Plane plane;
Collider col;
if (plane.Intersects(col)) // or the other way around col.Intersects(plane)
{
// Do stuff
}
Since I could not find such a function I created a test using the collider.bounds and testing for each point in the bounds, but I get a few false positives depending on the orientation of the collider and the plane. Any ideas on how to solve this?
Edit: One such false positives is when you have capsule collider rotated by 45 degrees and the plane is also oriented 45 degrees, the capsule could be completely on one side of the plane, but close enough to the plane that two of its bounding box vertices are on the other side of the plane, something like this:
| /
| /
| ...c
| . c.
| /.c .
| / c...
|/
+-------------
/ = plane
c = capsule
. = capsule bounding box limits
Ok, I did a workaround that solves my problem, though it's not the best solution, it's lightwheight enough and works for me. I check for the bounding box first and if the box collides, I check against the collider.
I found out that for spheres, capsules and boxes that's just some basic geometry, other types of colliders might be harder but I don't need to check against them so it's no problem for me.
Now I think the question is more of a feature request, as I think it should be a built-in function, a PlaneCast, working much like Raycasts do.
You could add a box collider of very thin dimensions to the Plane
object. Then the physics engine will automatically identify any collisions for you and initiate the OnCollisionEnter()
or OnTriggerEnter()
methods, so you don't need to manually check for them.
Will that work?
It could work, but I don't want to do that, performance is an issue and the plane is not fixed, it changes constantly so a box collider with triggerEnter would not be a lightweight solution I believe.
I would think that the built-in unity functionality would perform better than hand tailored solutions, but I can't prove it... Anyway, if you want to write it yourself, at least share your code and give examples of false positives so we can try and help you fix it.
But using a box collider is a hack, not a real built-in solution, it's like using a sphere collider and check all trigger enters ins$$anonymous$$d of a Physics.SphereCastAll. I'm pretty sure if your sphere would change size and position a lot, you'd be better off using periodic spherecasts (something like 1-5 per second) than using a sphere collider and changing it's size and position and all. Anyways, I'm thinking of a few solutions and about to implement them and test.