Hi there, I have a script that allows me to keep a camera between 2 players and always keeping them in the view of the screen but I’m looking to do this same system with 4 players.
I have tried a view different tactics but nothing seems to be working? I Have also tried google and nothing came of that has been any use to me.
Would someone perhaps be able to solve my issue? The script will be below.
Thanks in Advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraControl : MonoBehaviour
{
public Transform m_Player01;
public Transform m_Player02;
public Transform m_Player03;
public Transform m_Player04;
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;
private float _TanFov;
void Start()
{
_AspectRatio = Screen.width / Screen.height;
_TanFov = Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView / 2.0f);
}
void Update()
{
// Position the camera in the center.
Vector3 newCameraPos = Camera.main.transform.position;
newCameraPos.x = _MiddlePoint.x + 10f;
newCameraPos.y = _MiddlePoint.y;
newCameraPos.z = _MiddlePoint.z;
Camera.main.transform.position = newCameraPos;
// Find the middle point between players.
Vector3 vectorBetweenPlayers = m_Player02.position - m_Player01.position;
_MiddlePoint = m_Player01.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);
}
}