Fit object to screen

Just started to learn Unity and got stuck on a small thing.

I’m displaying a simple model, allowing the user to rotate and scale the object. Now I want to give the user the possibility to click any child of the object and having the camera zoom in. I have pretty much everything set up and working but I’m only able to zoom the camera in to the child objects 0,0,0-point…

I want the camera to calculate and stop when the object is centered and not more than 50 px from any part of the screen.

Any help/code (js) would be very appreciated, thanks!

I don’t know how to do it by moving the camera around, but try scaling the model instead.

var model : Transform;
function Update()
{
var scal = this.camera.WorldToScreenPoint(model.position).z;
model.localScale = 0.5 * Vector3(scal,scal,scal);
}

Try that code on a cube, it should expand and contract as the camera moves, so that it always looks the same relative scale on the screen.

Thanks, I’ll have a look what I can do with that. But I don’t want to scale the model since I have so much code in place that is just using the camera now.

Maybe I’m going the wrong way… any further help is appreciated! :slight_smile:

I don’t have the complete solution at hand, but here’s the basic recipe:

  1. Find out the size of the object (using: Unity - Scripting API: Bounds)

  2. Knowing the camera’s frustum / FOV, you can then do some trig to compute at what distance the object fills the screen.

  3. Move the camera to that distance from the object’s position.

Thanks you, sounds like a good approach!

I have the easy parts 1 and 3 covered but need some help with the part 2 calculations I think…

It feels like this should be a pretty standard thing to do in Unity so I was looking for some kind of zoomTo function at first. Maybe this would be something for Ani.Mate :slight_smile:

I basicly want to set my clicked child objects pivotpoint as the parents “master” pivot point and zoom the camera so the child fits the screen. Then, when I rotate the parent with all objects, it rotates around the selected child. I will see what I can come up with but further help would be great!

Love the community btw, feels like Flash in the old days :smile: