- Home /
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: http://youtu.be/uHlulsVgHzc?t=2m14s
Answer by robertbu · Mar 27, 2014 at 07:08 AM
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);
}
Hi there, I'm working on something similar and this is exactly the effect I'm looking for, although I'm trying to get this to work not just on the y axis from the ground, but from all sides. If my object was to slide left, right, up, or down I'd like the camera to zoom out to keep it in frame.
I've tried editing this with no luck on getting it to work, unfortunately. Could you explain how I could achieve this effect?
Honestly, thank you, I used this idea converted to a c# code for a problem that had been annoying me for weeks!!! Another pla$$anonymous$$u reached!