Other way of camera implementation

For once I made something that I like over the lecture’s implementation :slight_smile:

In hiearchy I made 2 new objects

  1. Cinemachine
  2. Empty object, named “CameraFollower”, which is looked at and followed by cinemachine

image

Then I made a simple script which is attached to “CameraFollower”

The code looks like this:

public class PlayerCameraRerouter : MonoBehaviour
{
    private NetworkObject networkObject;
    private PlayerMovement playerMovement;
    public void Start()
    {
        BindCamera();
    }

    private void OnDestroy()
    {
        if (playerMovement != null)
        {
            playerMovement.OnDespawn.RemoveListener(UnBindCamera);
        }
    }

    private void BindCamera()
    {
        var playerObjects = FindObjectsOfType<PlayerMovement>();
        foreach (var item in playerObjects)
        {
            if (item.TryGetComponent<NetworkObject>(out networkObject))
            {
                if (networkObject.IsOwner)
                {
                    transform.position = item.transform.position;
                    transform.parent = item.transform;
                    playerMovement = item;
                    item.OnDespawn.AddListener(UnBindCamera);
                    return;
                }
            }
        }
    }

    private void UnBindCamera()
    {
        transform.parent = null;
    }
}

Basically what it does is, when scene starts it will look for PlayerMovement class, which is basically on player prefab, checks if it’s owner and attaches the “CameraFollower” object as child

Note: I use UnitiyEvents instead of basic c# delegates

It’s more convenient - you don’t have to spawn many Cinemachines as players join, you just have one on scene which is attached to a player prefab that is a owner of current run

Works perfectly fine, when multiple player join

Had to develop it in previous lectures, becaues I needed for testing and convenience

Btw you can also use Cinemachine’s camera confiner If you don’t want to camera look beyond map border

just add extenstion for you cinemachine here

Then create empty gameobject with either box collider or polygon collider, resize the collider bounds to cover the whole map with it

Don’t forget to mark is trigger attribute, otherwise you’ll get stuck

once done, in Cinemachine object link to it:

After everything done correctly the camera whilst playing wont go beyond these bounds:

.

Privacy & Terms