Search Unity

2D camera tracking multiple targets

Discussion in 'Scripting' started by LEGEND383, Aug 30, 2015.

  1. LEGEND383

    LEGEND383

    Joined:
    Aug 1, 2012
    Posts:
    20
    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?
     
  2. robin-theilade

    robin-theilade

    Joined:
    Jun 3, 2012
    Posts:
    119
    Try this.

    CameraController.cs
    Code (CSharp):
    1. using System.Linq;
    2. using UnityEngine;
    3.  
    4. public class CameraController : MonoBehaviour
    5. {
    6.     public Camera cam;
    7.  
    8.     private void Update()
    9.     {
    10.         var targets = GameObject.FindObjectsOfType<MeshFilter>();
    11.         var minX = targets.Min(t => t.transform.position.x);
    12.         var maxX = targets.Max(t => t.transform.position.x);
    13.         var minY = targets.Min(t => t.transform.position.y);
    14.         var maxY = targets.Max(t => t.transform.position.y);
    15.         var desiredWidth = maxX - minX;
    16.         var desiredHeight = maxY - minY;
    17.         var currentWidth = Screen.width;
    18.         var currentHeight = Screen.height;
    19.         var targetSize
    20.             = desiredWidth > desiredHeight
    21.             ? ((desiredWidth / currentWidth) * currentHeight) / 2.0f
    22.             : ((desiredHeight / currentHeight) * currentWidth) / 2.0f
    23.             ;
    24.         targetSize += 1.0f;
    25.         this.cam.orthographicSize = Mathf.Lerp(this.cam.orthographicSize, targetSize, Time.deltaTime);
    26.  
    27.         var position = this.cam.transform.position;
    28.         position.x = maxX * 0.5f + minX * 0.5f;
    29.         position.y = maxY * 0.5f + minY * 0.5f;
    30.         this.cam.transform.position = position;
    31.     }
    32. }
    33.  
    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
     
    hahahpizza and cwmanley like this.