- Home /
Finding the bounds of a grouped model
I am importing a 3d model which consists of many smaller sub-parts; I would like to have a script to fire whenever the user clicks on any of the sub-part of the model. I could take a a cube gameobject and enclose it and disable the rendering, but I will have to manually size the cube.
Is there anyway to calculate the bounding area of such a grouped model? And how could I scale the cube to match that bounding area?
Answer by Eric5h5 · May 24, 2010 at 08:43 AM
You can iterate through the objects and use Encapsulate to add to the total bounds from the renderers:
var combinedBounds = renderer.bounds;
var renderers = GetComponentsInChildren(Renderer);
for (var render : Renderer in renderers) {
if (render != renderer) combinedBounds.Encapsulate(render.bounds);
}
That returns the bounds in world space; you can use mesh.bounds to get bounds in local space.
How do I assign this bound correctly to the parent object so that its collider's size can encapsulate the child objects? Should I use BoxCollider.size?
@Extrakun: use collider.bounds, and use type Collider with GetComponentsInChildren.
This code won't work unless all the all maxima have all positive values and all $$anonymous$$ima have all negative values. You need to define the cumulative bounds by the bounds of the first render.
Once again Eric5h5 to the rescue. I spent ages looking into this...
Answer by tgouala-wellfiredLtd · Feb 27, 2016 at 03:57 PM
Here a snippet to get the local bounds which works for any model, no matter it is rotated or not :
private void CalculateLocalBounds()
{
Quaternion currentRotation = this.transform.rotation;
this.transform.rotation = Quaternion.Euler(0f,0f,0f);
Bounds bounds = new Bounds(this.transform.position, Vector3.zero);
foreach(Renderer renderer in GetComponentsInChildren<Renderer>())
{
bounds.Encapsulate(renderer.bounds);
}
Vector3 localCenter = bounds.center - this.transform.position;
bounds.center = localCenter;
Debug.Log("The local bounds of this model is " + bounds);
this.transform.rotation = currentRotation;
}
this can apply for case that we want to add a box collider to a gameobject (3d model) which consists of many smaller sub-parts
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Adding force to a bullet 3 Answers
Changing 3d text through script 1 Answer
Creating a bounding box for multiple objects using bounds 2 Answers
3D Menu Help 1 Answer