- Home /
Question by
yackbladder · Dec 22, 2015 at 09:03 AM ·
camerarendererlistsboundsencapsulation
Want to frame multiple objects in camera view using render bounds
Hello, I am trying to get the camera to frame multiple spawned objects. When I try this with a single item the camera frames it properly but when I try with a list of items the camera moves to 0,0,0.
The objects are visible in the scene.
Each GameObject has a child with a Mesh Renderer and Box Collider.
I add the objects to a list (gridSCR.listOfGridTiles) when they are spawned. The objects are definitely in the list
Here is my C# code:
public Bounds CalculateBounds(GameObject objectToCheck) {
Bounds bounds = new Bounds(objectToCheck.transform.position, Vector3.zero);
Object[] rList = objectToCheck.GetComponentsInChildren(typeof(Renderer));
// Get the bounds of each childs renderer
foreach (Renderer r in rList) {
// Add the bounds together
bounds.Encapsulate(r.bounds);
}
return bounds;
}
public void ZoomToAll(){
Bounds totalBounds = new Bounds();
// Loop through a list of game objects
for (int i = 0; i < gridSCR.listOfGridTiles.Count; i++){
// Add the bounds of each game object together
totalBounds.Encapsulate (CalculateBounds(gridSCR.listOfGridTiles[i]));
Debug.Log("Total bounds = " + totalBounds);
}
Vector3 max = totalBounds.size;
float radius = Mathf.Max(max.x, Mathf.Max(max.y, max.z));
float dist = radius / (Mathf.Sin(mainCamera.fieldOfView * Mathf.Deg2Rad / 2f));
Debug.Log("Radius = " + radius + " dist = " + dist);
// Position the camera at the bounds center
mainCamera.transform.position = totalBounds.center;
// Offset the camera to frame object
mainCamera.transform.Translate (0 ,0, -dist);
}
Debug log from above: Total bounds = Center: (0.0, 0.0, 0.0), Extents: (0.0, 0.0, 0.0)
I'm a coder noob so any help you could provide would be greatly appreciated. :)
Thanks in advance. - yackbladder
Comment