- Home /
How to detect that my object is completely inside a box?
Hi,
I'm developing a game that you drag and drop objects into boxes and I have no idea what's the best and most efficient way to detect whether my objects are in a box.
I'm well aware of colliders and I'm using BoxColliders and triggers to find out whether my object is touching a box but I want to detect the moment when my object (which we can assume to be sphere for sake of simplicity but later will be a mesh) is completely inside my box trigger/collider.
I read about "Contains" method of colliders but IIRC they just check if one single point inside that collider but I'm interested to know if the whole object is inside the collider.
Thanks in advance folks.
Answer by Owen-Reynolds · Oct 27, 2012 at 04:21 PM
A simple, crude way is to just check if you're near the exact center of the box. Not perfect, but works surprisingly well.
If the dragged objects have capsule, box ... colliders, simply shrinking your trigger will work. To work out the size, draw some pictures with your object not quite placed, and barely counts as placed.
If you've got oddly-shaped things and need each tentacle and tail to be completely in, that's a tougher nut.
Could rig up an "inside me" collider using four box collider "walls." Each wall adds one to the dragged object's `wallCount` on enter, and subtracts one on leave. If your `wallCount` is 0 and your position is within the box bounds, you're completely in. Bonus is you could "flash" the offending wall as a placement guide.
Thanks for your answer but:
1) I can't check if they are near the center because in the actual game, this may not happen and I will it.
2) $$anonymous$$y dragged objects will have like sphere colliders Shrinking my trigger will not work as well because I use that trigger to find out about the collision itself.
3) About the four walls suggestion, the same problem will happen that how you will know when an object is passed from that specific wall, hence you have to know when it's inside the wall and same problem occurs.
So are your boxes much larger than the objects? Even then, say you have 5x5 boxes and size 1 objects. A 4x4 trigger will give a pretty close "fully inside" check.
Each wall is one thin side, so as an object moves into the box it starts not in the wall, in the wall (passing through it) and then outside the wall again (in the box.)
Your answer
Follow this Question
Related Questions
physics.OverlapSphere colliders 1 Answer
What are best practices for getting your character to not fall through the floor? 1 Answer
Strange Collisions in 2D 1 Answer
An object with multiple rockets? 1 Answer
Trigger-based vehicle ai? 1 Answer