Scale object to fit within of a sphere

Hi,

I can’t seem to figure out the following in a script:

I have an gameobject (prefab) that is irregular in shape, which I want to rescale to fit within a transparent sphere. (use case: I want to create a socket system - the sphere - to store items in).

I have played around with getting the bounds of the object that I want to store through the following:

var colliders = storedObject.GetComponentsInChildren();
var boundsOfStoredObject = new Bounds(Vector3.zero, Vector3.zero);
foreach (var c in colliders) boundsOfStoredObject.Encapsulate(c.bounds);

But not sure how to get the correct scale from these bounds to fit the sphere.

Any help would be highly appreciated!

Try prefabScale = sphereRadius / boundsOfStoredObject.max.magnitude
Assuming your prefab and sphere are centered at zero.

Just to add an explanation to this: the idea is that you want to figure out the longest side of the bounding box of your item. Once you have that, you can determine your scaleFactor by calculating sphereRadius / longestBoxSide. Scaling your object down on all axis by the scaleFactor effectively makes it so that the longest side of the model touches the sphere, while everything else of the model is contained inside of it, since the model was smaller on those axis. In reality you probably want to add some padding around the bounding box before calculating the scaleFactor, such the the items become a bit smaller than necessary and thus visually look better contained in the sphere.

1 Like

@mbaske Thank you very much!

@Yoreki Thank you for explaining this to me!

Would you minde helping me a little more, as I do still get strange results in scaling (object getting really small, which are already smaller than the sphere, or too small in general). Pretty new at this, and math isn’t my strongest side apparently.

So I now have:

(this script is on the sphere which should contain the object)

var meshFilter = storedObject.GetComponent().mesh.bounds;
var scaleFactor = GetComponent().radius / meshFilter.max.magnitude;
var scale = new Vector3(storedObject.transform.localScale.x * scaleFactor,
storedObject.transform.localScale.y * scaleFactor,
storedObject.transform.localScale.z * scaleFactor);
storedObject.transform.localScale = scale;

Do you see anything obviously wrong?

(I switched to the meshfilter for the bounds, as the colliders were giving me weird bounds. Ex. an object which has for an transform.y value 5000, also have bounds of 5000+, while the colliders are just encompassing the object)

Maybe something to note is that most of the objects that I try to downscale, are already downscaled by default (so standard cubes have been scaled to 0.1 for example)

Maybe try using Bounds.extents instead of Bounds.max, since max takes the center position into account.
Have you drawn some debug lines to see how your Vector3s are positioned?