I’m downloading assets at runtime and fixing them up dynamically. One of the things I need to do is add a BoxCollider to an object that has a renderer on it, and make the box collider perfectly fit overtop the rendered object. Renderer has a variable bounds
which returns its bounds in world coordinates. BoxCollider has two members, center
and size
, which are in local coordinates. So what I need to do is convert the Renderer’s world-coordinates Bounds into a local-coordinate center and size. This is the code I have:
BoxCollider box = myRenderer.gameObject.AddComponent<BoxCollider>();
box.isTrigger = true;
box.center = myRenderer.transform.InverseTransformPoint(myRenderer.bounds.center);
box.size = myRenderer.transform.InverseTransformDirection(myRenderer.bounds.size);
This code works for SOME objects, but not others. It depends on what other transforms are parented above the renderer. In other words, it’s not transforming it right all the time. The center point is usually (maybe always?) correct, but the size variable is often wrong. The box is the right size, but it isn’t aligned correctly over the renderer. It’ll be perpendicular in one or more dimensions, e.g. on an object that’s that’s long and squat, the collider will be tall and thin.
I guess the InverseTransformDirection() function can’t correctly transform a vector that contains a size? What can?
Can someone explain what’s going wrong, and what I can do about it?
Thanks!