- Home /
Keep GameObject in Camera View as it Grows Vertically
I have a group of gameobjects that "grow" vertically (think of a plant growing). The camera view starts at the ground level, where the plant sprouts from the dirt. I would like to have the camera smoothly zoom out as the plant grow to keep the entire plant in view. How would I go about doing this?
I know that I can use the minimum/maximum Y values, but how do I use that to position the camera so that the objects are within the camera's field of view?
Thanks!
Answer by hathol · Jun 25, 2012 at 11:27 PM
probably not the most efficient way since my maths skills are still a bit rusty, but it will work (or at least give you a starting point) :)
public GameObject m_target;
void Update ()
{
float gamma = camera.fieldOfView/2f;
float alpha = 90f-gamma;
float c = Mathf.Abs(m_target.transform.localScale.y/2f);
float sinA = Mathf.Sin(alpha*Mathf.Deg2Rad);
float sinC = Mathf.Sin(gamma*Mathf.Deg2Rad);
// a/sin(alpha) = c/sin(gamma)
// a = (c*sin(alpha))/sin(gamma)
float a = (c*sinA)/sinC;
Vector3 newPos = m_target.transform.position; // assuming the object pivot is at its center
newPos.z -= a+3; // give it a bit of extra space
transform.position = newPos;
}
$$anonymous$$, this works great! THAN$$anonymous$$ YOU. I couldn't have figured this out without your help. Now I just need to add some lerping to smooth out the new position change.
Now I just wish I had paid more attention during my math courses :). Just out of curiosity, if I wanted to learn the math behind this, what should I google?
Thanks again :).
Don't worry, you'll learn most of it as you go along :). For the maths behind: just search for "solving a triangle". We have a given side (c, your y extents) and 2 given angles (FOV/2 is the angle for c and since the camera is looking straight at the object, the angle between that axis and c must be 90 degrees). Then you can just use the law of sines to solve it ( I googled that one ;) )
Your answer
![](https://koobas.hobune.stream/wayback/20220613073257im_/https://answers.unity.com/themes/thub/images/avi.jpg)