Camera Script : Focus two objects | Unity3d

Uncategorized

A Camera Script for focusing two objects in the Scene.The below script adjust camera position in such a way to focus the two given object

Keywords : Unity camera focus object | Unity3d Camera follow

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CameraZoom : MonoBehaviour {
 
public Transform player1;
public Transform player2;
 
private const float DISTANCE_MARGIN = 1.0f;
 
private Vector3 middlePoint;
private float distanceFromMiddlePoint;
private float distanceBetweenPlayers;
private float cameraDistance;
private float aspectRatio;
private float fov=40;
private float tanFov;
 
void Start() {
aspectRatio = Screen.width / Screen.height;
tanFov = Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView / 1.5f);
}
 
void Update () {
// Position the camera in the center.
Vector3 newCameraPos = Camera.main.transform.position;
newCameraPos.x = middlePoint.x;
Camera.main.transform.position = newCameraPos;
 
// Find the middle point between players.
Vector3 vectorBetweenPlayers = player2.position - player1.position;
middlePoint = player1.position + 0.5f * vectorBetweenPlayers;
 
// Calculate the new distance.
distanceBetweenPlayers = vectorBetweenPlayers.magnitude;
cameraDistance = (distanceBetweenPlayers / 2.0f / aspectRatio) / tanFov;
 
// Set camera to new position.
Vector3 dir = (Camera.main.transform.position - middlePoint).normalized;
Camera.main.transform.position = middlePoint + dir * (cameraDistance + DISTANCE_MARGIN);
}
}