Encapsulate.Bounds is no longer working.

Hey guys! I’m back :stuck_out_tongue:
I am having a BIG issue which is halting my development phase severely!

#pragma strict
 
var boundsForwadPoint : Vector3;
 
function Update()
{
    EncapsulateAll();
}
 
function EncapsulateAll()
{
    var combinedBounds = new Bounds();
    var renderers = GetComponentsInChildren(typeof(Renderer));
    for (var renderer : Renderer in renderers)
    {
        if (renderer != this.renderer)
            combinedBounds.Encapsulate(renderer.bounds);
    }
 
    boundsForwadPoint = combinedBounds.center + new Vector3(0, 0, combinedBounds.max.z);
}
 
function OnDrawGizmos()
{
    Gizmos.DrawSphere(boundsForwadPoint, 0.25);
}

This is my code, for some reason it has stopped changing the center point of my gameObject.
What this script is supposed to do, (as you can probably tell :P) is constantly update the middle point of a parent gameobject so the pivot point continuously changes if the gameobject is altered.

For example:

I am using this for a ship building feature in one of my games. Each ship is constructed by combining a group of cubes onto a parent.

Each cube which is added is supposed to change the bounds.center of the entire ship, so the parent object is constantly in the middle of the creation instead of at the parents center location.

Now for as long as I can remember, it has always worked, even the gizmo is being drawn properly, but the gameobject which is the parent isn’t being moved.

//

Is there anything you guys can see that i am missing? :frowning: Or am i on the totally wrong track here.

//

I hope this is all the information you guys need.
Any help would be appreciated.

Thank you for reading, Sincerely,

Bakos133

I see two major problems here:

  • First you initialize your combinedBounds with an empty “bounds object”. That means it’s centered at the scene origin and has no size. When you encapsulate other bounds that aren’t around 0,0,0 the resulting bounds object wouldn’t be correct.
  • Second you use the bounds center and add the bounds max z-value, that doesn’t make much sense. You probably want to add Bounds.extents.z to get the end position of the bounds volume.

The bounding box is defined in world space. You should initialize the combinedBounds either with the objects position or, which would be better, with one of the child bounds.

Something like this:

function EncapsulateAll()
{
    var renderers = GetComponentsInChildren(typeof(Renderer));
    if (renderers.Length == 0)
        return;
    var combinedBounds = renderers[0].bounds;
    for (var renderer : Renderer in renderers)
    {
        if (renderer != this.renderer)
            combinedBounds.Encapsulate(renderer.bounds);
    }
    boundsForwadPoint = combinedBounds.center + new Vector3(0, 0, combinedBounds.extents.z);
}