Keeping two objects in frame

I am working on a 2D endless runner and I am having a hard time trying to figure out how to “zoom” the camera in and out based on the height of the player from the ground while keeping both the player and the ground in view. I am trying to change the size of my orthographic camera, but just doing that alone doesn’t get the effect that I am trying to accomplish. Any help would be greatly appreciated.

Here is the effect that I am going for: - YouTube

Here is a bit of code to get you started. I’m assuming an orthographic camera. Variables explained:

  • target - object to follow
  • bottom - world ‘y’ position that will be right at the bottom of the camera no matter what the ortiographicSize is set to.
  • lead - world units on how much to lead the target. You could add code to vary this value based on the orthographic size.
  • above - amount of space to leave above the pivot of the target
  • minView - the lower limit to the world units seen by the camera. That is, if the distance between the bottom and the target plus the above is less than this amount, the camera will no longer zoom. I added this based on what I saw in the video.

This script should be added to the camera:

#pragma strict

var target : Transform;
var bottom : float = -4.0;  // Bottom edge seen by the camera
var lead : float = 2.5; // amout to lead the target
var above : float = 1.5; // amount above the target pivot to see
var minView : float = 7.5;

function LateUpdate() {
	var height = target.position.y + above - bottom;
	height = Mathf.Max(height, minView);
	height /= 2.0;
	camera.orthographicSize = height;
	transform.position = Vector3(target.position.x + lead, bottom + height, -10);