Created
January 18, 2018 12:34
-
-
Save arunkarnann/93529e679b04aadbaf6eaab5e9418323 to your computer and use it in GitHub Desktop.
Unity 3d Camera Script calculate postion to move the camera to show two Game objects inside the camera. || Show two game objects in camera .
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment