- Home /
How do I adapt Brackey's Multiple Target Camera for a 2D game?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Camera))]
public class MultipleTargetCamera : MonoBehaviour
{
public List<Transform> targets;
public Vector3 offset;
public float smoothTime = .5f;
public float maxZoom = 40f;
public float minZoom = 10f;
public float zoomLimiter = 50f;
private Vector3 velocity;
private Camera cam;
void Start()
{
cam = GetComponent<Camera>();
}
void LateUpdate()
{
if (targets.Count == 0)
return;
Move();
Zoom();
}
void Zoom()
{
float newZoom = Mathf.Lerp(maxZoom, minZoom, GetGreatestDistance() / zoomLimiter);
cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, newZoom, Time.deltaTime);
}
void Move()
{
Vector3 centerPoint = GetCenterPoint();
Vector3 newPosition = centerPoint + offset;
transform.position = Vector3.SmoothDamp(transform.position, newPosition, ref velocity, smoothTime);
}
float GetGreatestDistance()
{
var bounds = new Bounds(targets[0].position, Vector3.zero);
for (int i = 0; i < targets.Count; i++)
{
bounds.Encapsulate(targets[i].position);
}
return bounds.size.x;
}
Vector3 GetCenterPoint()
{
if (targets.Count == 1)
{
return targets[0].position;
}
var bounds = new Bounds(targets[0].position, Vector3.zero);
for (int i = 0; i < targets.Count; i++)
{
bounds.Encapsulate(targets[i].position);
}
return bounds.center;
}
}
this is the script I was left with after watching and following along with Brackey's "Multiple Target Camera" tutorial. however, the game he is making in the tutorial is 3D and my game is 2D. the field of view (used in the void Zoom() ) is not available on a 2D camera. so how should I work around this? is there code for zoom on a 2D camera? or do I have to use a 3D camera, and set the z to 0 on all the objects? please help! thanks!
Answer by RealFolk · Jan 23, 2021 at 06:18 PM
Adjusting a 2D cameras size will zoom in and out like field of view on a 3D camera.
void Zoom()
{
float newZoom = Mathf.Lerp(maxZoom, minZoom, GetGreatestDistance() / zoomLimiter);
cam.orthographicSize = Mathf.Lerp(cam.orthographicSize, newZoom, Time.deltaTime);
}
thanks! works like a charm! this is exactly what I needed :D
Your answer
Follow this Question
Related Questions
ortographic camera smooth follow with zoom 1 Answer
Fighting Game Camera 1 Answer
2D camera zoom in comparison to the height of target 2 Answers
2D camera zoom smoothing and limitations? 1 Answer
Zoom Pinch 1 Answer