Scaling gameobject depending on camera view

Hey.

Before I start : nope, I’m not trying to scale a plane depending on the screen size :stuck_out_tongue: All topics I found about scaling objects was about that and it is not what I want.

In my scene, I have a camera which is looking a pedestal.

In my UI, I need to show what the camera is looking, so to do that, I’m using a Render Texture. Everything is OK for that.

2050736--133345--UnityRenderTexture.png

My goal is not to look the pedestal but the GameObject I’m spawning at one point. And here is my problem: the GameObject I spawn can be anything : something small or something really big.

2050736--133346--UnityResult.png

I want this GO to fit my camera view… If it is small, I need it to be bigger or if it is big, I need it to be smaller. I don’t know how I can do that.
I know the distance between the Camera and the Spawn point. I guess I can know the box size of the GO with Bounds…

If someone has any tips… :sunglasses:

Thank you!
Sbizz.

There’s lots of ways to do that - probably a simple way would be to do something like this:

  1. Camera position starts in centre of pedestal

  2. Get bounding radius of the game object (Unity - Scripting API: Renderer.bounds)

  3. Multiply this radius by 2 and then add some extra onto it

  4. Multiply camera pointing vector (forward vector) by the negative radius and add that to it’s current position

  5. The camera should now be pointing at the object

I did something better and it works perfectly, using the bounds:

    private void AutoScaleObject(GameObject GO) {
        // Get the bounds reference (the size of GO should be the same)
        Bounds boxScalerBounds = _elements.BoxScaler.bounds;

        // Get the GO bounds
        Bounds GOBounds = GO.GetComponent<Renderer>().bounds;

        // Get the difference between the radius (is it smaller or bigger ?)
        float percent = GOBounds.extents.magnitude / boxScalerBounds.extents.magnitude;

        // Depending on the percent, adjust the scale
        Vector3 finalScale = GO.transform.localScale * ((percent > 1) ? (1 / percent) : (1 + (1 - percent)));

        GO.transform.localScale = finalScale;
    }

I have to check the percentage again because when the GO is really small, It still is too small. But all big objects (> 1) are well scaled !

Good stuff, it’s probably not going to be accurate at small sizes because the camera has perpsective on it so you might need to factor that in somehow.