- Home /
Looking for CheckCube
I have to check for a free space in a virtual world of cubes (or mashes with a CubeCollider) to initiate a new Object. But what is the most elegant method to check for a free space? Of course CheckCapsule
or CheckSphere
is exact what I'm looking for, only that they are not for Cubes.
Initiating the rigidbody with a collider and check a collision is not possible, because initiation is not a move, so there is no collision or trigger.
SweepTest is a nice function, but not for a new object.
So, is there something like CheckCube?
Answer by robertbu · Oct 08, 2014 at 08:29 AM
No built in function. Assuming you want to check some cubic space for an intersection, you can do it by 'hand'. Generate a bounds for the space you want to check, then cycle through all the game object and check their colider.bounds against the bounds of the test area. A bit of untested code:
function IntersectBounds(bounds : Bounds, objects : GameObject[]) : boolean {
for (var go : GameObject in objects) {
if (bounds.Intersects(go.collider.bounds)) {
return true;
}
}
return false;
}
Note if you are going to be doing this a lot or have a large number of cubes, it might pay to build an array or generic List of colliders, and pass than in instead of an array of game objects. Note due to floating point inprecision, you might need to make the bounds test space just a smidgen smaller to avoid false positives.
Thanks for your fast answer! That was my next thought, but I hoped that it was not necessary. :)
But it does only work with world-space axis-aligned cubes!
Well, it only check a space defined by a bounds which is a rectangular, 3D, axes aligned space, but the object being placed does not have to be a cube.
But if the cube is not aligned, the testing bounds are much too large.
I'm unclear about the nature of the issue. Whether you are trying to place a rotated cube, or if you are trying to see if a rotated code can be axes aligned and then placed. If the latter, you can use mesh.bounds and then scale the result by Transform.localScale, or you can set the rotation to Quaternion.identity before reading the renderer.bounds, restoring the rotation if necessary.
Your answer
Follow this Question
Related Questions
Rolling Cube with Rigidbody? 5 Answers
Random Genration of Cube 2 Answers
Finding the dimensions of a cube, exploiting them. 2 Answers
instantiate works on one but not other object 0 Answers
How to add vertices to a cube 1 Answer