- Home /
How to detect what percentage of an object is inside a trigger?
If the player is controlling a sphere and I want the game to end when the sphere enters a goal volume (a cube collder), how can I detect if the sphere is entirely/95% inside the trigger, not just touching it?
that's impossible! at least in javascript, i dont know ANYTHING about c+, but im sure there's some complicated script just for that.
It is actually possible. And, language independent. You could do it in JS or C#. Unity does not have any built-in routine for checking that but I would search for it in your browser, or pick up a book on geometry. The formula is probably rather complicated, but you could implement it in Unity just like any other algorithm. And since you are using spheres and cubes, the volume is easy to find.
It is actually very simple, at least when it comes to the OBB and sphere. You just need a bit of linear algebra... =)
Answer by Eric5h5 · Oct 26, 2010 at 02:46 AM
How about getting the distance between the sphere's position and the cube collider's position...if it's a smaller distance, then a larger percentage of the sphere is inside the cube, more or less. That would only work perfectly for two spheres, but it would generally work for a sphere and a cube.
A tutorial elsewhere got me thinking of this solution and it ended up working well.
Answer by Tobbe Olsson · Oct 26, 2010 at 01:07 AM
I would set up multiple gameobjects with triggers that are based on the percentage you want. That's how I've done proximity mines and other proximity based solutions. Sounds like a lot easier of a solution too!
If you are making a soccer type goal, I would just place the collider inside the goal so when it touches the collider and triggers it, it would only count as a goal because you placed it at 95% of the diameter of the ball inside the goal.
I like it. Especially if the OP doesn't need perfect accuracy. Vote up :).
Answer by IJM · Oct 26, 2010 at 04:13 AM
You can combine transformation matrix of your Box GameObject and it's BoxCollider.size to get OBB. Once you have a OBB, you can combine rotation matrix of your Box with Sphere's radius and Sphere's position to get 6 points. The only thing left to do is check if these points are located within the OBB. If all 6 points are inside, sphere is 100% inside. Quite simple.
Answer by Herman-Tulleken · Oct 26, 2010 at 05:01 AM
A sphere is approximately 95% inside a trigger if it is touching a smaller trigger.
So simply make your trigger smaller.
In this case, make the dimensions of the trigger smaller by [some value] of the diameter of the sphere. You can calculate [some value], or, just use an easy value (like 95% of the diameter) This is, like I said, just an approximation, but you wouldn't be able to tell it visually from the real thing.