2 Players 1 Camera

How would i go about on creating camera that followed 2 players but it would limit to lets say when one player is at the left border of the camera and the other player cannot move anymore unless the other player would move right.

Here my crack at the script, but this did not work.

I tried to check if the players were moving left or right and when the distance were to far apart the camera object couldn’t move anymore. This didn’t work as plan because the camera still moved, not sure why

Could someone lead me the way to a better way to achieve this? Or examples?

using UnityEngine;

public class TwoPlayerCam : MonoBehaviour 
{
    public GameObject Player1;
    public GameObject Player2;

    public Camera CameraMove;
    public float MaxDistance;

    public bool camCanMoveLeft = true;
    public bool camCanMoveRight = true;

    void Start(){

        Player1 = GameObject.FindGameObjectWithTag("player1");
        
        Player2 = GameObject.FindGameObjectWithTag("player2"); 
        MaxDistance = camera.orthographicSize;
    }

    void Update()
    {
        var rotation1 = Player1.transform.position;
        var rotation2 = Player2.transform.position;
        var P1Comp = Player1.GetComponent<CharMovement>();
        var P2Comp = Player2.GetComponent<CharMovementPlayerTwo>();

        var distance = Vector3.Distance(rotation1,rotation2);
        if (distance > MaxDistance && camCanMove==true){
            print("far");
            CameraMove.transform.position += new Vector3(.85f,0f,0f);
            camCanMove=false;
        } 
        else if (distance > MaxDistance && camCanMoveRight==true){
            print("far");
            CameraMove.transform.position += new Vector3(-.85f,0f,0f);
            camCanMoveRight=false;
        } 
        else if(MaxDistance > distance){
            camCanMoveRight=true;
            camCanMove=true;
        }

        if(P1Comp.state == CharMovement.WalkingState.WalkLeft || P2Comp.state == CharMovementPlayerTwo.WalkingState.WalkLeft && camCanMoveLeft)
            CameraMove.transform.position += new Vector3(-.85f,0f,0f);

        else if(P1Comp.state == CharMovement.WalkingState.WalkRight || P2Comp.state == CharMovementPlayerTwo.WalkingState.WalkRight && camCanMoveRight)
            CameraMove.transform.position += new Vector3(.85f,0f,0f);
    }
}

In that script you’re not setting camCanMoveLeft=false anywhere, that might be the problem.

Why not just directly set the camera position and prevent player movement if they’re too far from each other?

camera.position = (player1.position + player2.position) / 2.0;
// then also set the camera’s distance along the view normal so it’s not directly on the game plane

if ( distance > maxDistance ) player1.position = player2.position + (player1.position-player2.position).normalized * maxDistance;