I am trying to set up a camera that will track multiple players. It is an orthographic camera. So far, the camera stays centred between all of the players, but I’m having trouble getting the zoom right, so that it will zoom in as the players get closer and zoom out as they get further away from each other.
It needs to deal with the players moving on both the X and Y axis, but so far I can only get the zoom working when dealing with one or the other, and everything I’ve found only deals with one or the other. Anyone have any ideas on how to make the zoom work for both?
Try this.
CameraController.cs
using System.Linq;
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Camera cam;
private void Update()
{
var targets = GameObject.FindObjectsOfType<MeshFilter>();
var minX = targets.Min(t => t.transform.position.x);
var maxX = targets.Max(t => t.transform.position.x);
var minY = targets.Min(t => t.transform.position.y);
var maxY = targets.Max(t => t.transform.position.y);
var desiredWidth = maxX - minX;
var desiredHeight = maxY - minY;
var currentWidth = Screen.width;
var currentHeight = Screen.height;
var targetSize
= desiredWidth > desiredHeight
? ((desiredWidth / currentWidth) * currentHeight) / 2.0f
: ((desiredHeight / currentHeight) * currentWidth) / 2.0f
;
targetSize += 1.0f;
this.cam.orthographicSize = Mathf.Lerp(this.cam.orthographicSize, targetSize, Time.deltaTime);
var position = this.cam.transform.position;
position.x = maxX * 0.5f + minX * 0.5f;
position.y = maxY * 0.5f + minY * 0.5f;
this.cam.transform.position = position;
}
}
Just replace the line that finds the targets that must be within view so it works with your setup, attach the script somewhere and assign the camera to the script.
/Robin
2 Likes