I have a game set-up with 2 players, both with separate movement scripts of course. My main concern is that the camera must move with the player(s). I can parent the camera to just one player but then the other one can get left behind.
We’ll keep it simple and assume you have a camera with fixed rotation (it will be simple to further this functionality for a rotating camera (or any number of transforms) given a little work on paper):
// Follow Two Transforms with a Fixed-Orientation Camera
public void FixedCameraFollowSmooth(Camera cam, Transform t1, Transform t2)
{
// How many units should we keep from the players
float zoomFactor = 1.5f;
float followTimeDelta = 0.8f;
// Midpoint we're after
Vector3 midpoint = (t1.position + t2.position) / 2f;
// Distance between objects
float distance = (t1.position - t2.position).magnitude;
// Move camera a certain distance
Vector3 cameraDestination = midpoint - cam.transform.forward * distance * zoomFactor;
// Adjust ortho size if we're using one of those
if (cam.orthographic)
{
// The camera's forward vector is irrelevant, only this size will matter
cam.orthographicSize = distance;
}
// You specified to use MoveTowards instead of Slerp
cam.transform.position = Vector3.Slerp(cam.transform.position, cameraDestination, followTimeDelta);
// Snap when close enough to prevent annoying slerp behavior
if ((cameraDestination - cam.transform.position).magnitude <= 0.05f)
cam.transform.position = cameraDestination;
}
Make a script and attach it to the camera. Make the script change the position of the camera by averaging the vector 3 positions of all the active player gameObjects. You might have to average all x values and y values (assuming 2D) unless there is a method somewhere which does it for you.