- Home /
calculating the object bounds of the group of objects
i am trying to get the center of the group of objects, so that i can center the camera to that group and have all subobjects in the screen.
here is the code i am using:
var bound : Bounds= new Bounds(Vector3.zero,Vector3.zero); //all objects in the group have colliders, so i am using colliders to get bounds var Colliders = target.GetComponentsInChildren(Collider);
for(var collider : Collider in Colliders){ //if members are not tagged group or microlabel since these are just groups if(collider.tag!="group" || collider.tag!="microlabel"){ bound.Encapsulate(collider.bounds); } }
//print the center and size of the new bounding box Debug.Log("center: " + bound.center.ToString() + " size: " + bound.size.ToString());
//test the center of bounding box by creating the sphere with that position var sphere : GameObject=GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position=bound.center; //make sphere smaller so it fits the scene and marks more precisely the position sphere.transform.localScale=Vector3(0.2,0.2,0.2);
this works fine for group of groups of objects, but it does not calculate the group that only holds objects i have offset by the y axis, what to do? maybe i am missing something? how to calculate this type of thing properly?
thanks
EDIT:
ok i guess that i should use the mesh.bounds instead of collider bounds. it is harder to get those i think. can somebody help me replace collider bounds with mesh.bounds in the code i provided. any help appreciated!
using renderer.bounds ins$$anonymous$$d of collider.bounds gives the same result any help appreciated!
Answer by Ejlersen · Dec 16, 2010 at 08:07 PM
If you want to use the mesh.bounds, then you need to do something like this:
var filters = target.GetComponentsInChildren(MeshFilter);
for(var filter : MeshFilter in filters) { //if members are not tagged group or microlabel since these are just groups if(filter.tag!="group" || filter.tag!="microlabel") { bound.Encapsulate(filter.mesh.bounds); } }
I think that would work. Its of the top of my head :)
it doesn not makes spheres at correct position... maybe it has something to do with local space it dont know...so far using colliders at least gives me approximate position... do not know what is going on
No, you are correct. This is from the documentation for mesh.bounds:
"This is the axis-aligned bounding box of the mesh in its local space (that is, not affected by the transform). See also Renderer.bounds property that returns bounds in world space."
So try getting the $$anonymous$$eshRenderers ins$$anonymous$$d and use their bounding box.
Hope this solves your problem.
Your answer
Follow this Question
Related Questions
when should Mesh.Optimize() be called 1 Answer
How to calculate a Collider2D's bounds 0 Answers
get the height of a sprite at a specific point 0 Answers
Grouping Enemies/Targets 1 Answer
2D GUI Group moving with players. 1 Answer