Last active
March 24, 2022 08:24
-
-
Save GarethIW/e9900a45f535fa78016c05d1b0ee8105 to your computer and use it in GitHub Desktop.
Unity camera script for following and clamping to multiple players
This file contains hidden or 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
public class MainCamera : MonoBehaviour | |
{ | |
public Transform[] Players; | |
public Vector3 Target; | |
public Vector3 BaseOffset; | |
public float Speed; | |
public float YZoomFactor; | |
public float ZZoomFactor; | |
void Update () | |
{ | |
Vector3 max = new Vector3(Mathf.NegativeInfinity,0f, Mathf.NegativeInfinity); | |
Vector3 min = new Vector3(Mathf.Infinity, 0f, Mathf.Infinity); | |
for (int i = 0; i < Players.Length; i++) | |
{ | |
if (!Players[i].gameObject.activeSelf) continue; | |
if (Players[i].position.x < min.x) min.x = Players[i].position.x; | |
if (Players[i].position.z < min.z) min.z = Players[i].position.z; | |
if (Players[i].position.x > max.x) max.x = Players[i].position.x; | |
if (Players[i].position.z > max.z) max.z = Players[i].position.z; | |
} | |
Target = min + ((max-min)/2f); | |
Target.y = BaseOffset.y + ((Vector3.Distance(min, max)) * YZoomFactor); | |
Target.z = (min.z + BaseOffset.z) - ((Vector3.Distance(min, max)) * ZZoomFactor); | |
transform.position = Vector3.Lerp(transform.position, Target, Speed*Time.deltaTime); | |
transform.LookAt(min+((max-min)/2f)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.youtube.com/watch?v=eaivu2XvmH0