One question to consider: do you want to position the camera or zoom the camera (or perhaps do a blend of both)? Those are two different operations.
Step one is calculating the bounding volume that contains all of the players. This is pretty easy in C++, but looks like you’re interested in blueprints. The basic algorithm would be:
- Start with a MinBounds and MaxBounds vectors
- For each of your players:
GetActorBounds() on the player
Origin - Extents is less than MinBounds, overwrite MinBounds (so: set MinBounds to
Origin - Extents and MinBounds).
- Same for Origin + Extents being greater than MaxBounds (using the
Once that’s done, you’ll have two vectors that define the corners of a bounding box surrounding all of your players.
Next, we’ll want to position the camera so that it’s aiming at the center point of that box. We can calculate this point with
MinBounds + (MaxBounds - MinBounds) / 2.0.
Presumably, with a side-scroller, you have fixed horizontal, vertical, and depth axes. The camera is going to be positioned “back” along the depth axis. We need to calculate this distance.
This comes back to: are you wanting to position, zoom, or both to get the camera to see everyone?
Let’s assume your zoom (Field of View) is going to be constant. We now have a triangle defined on the horizontal plane:
\ | a
- o (opposite) = half of the horizontal bounds; if this is, say, the X axis, it would be
(MaxBounds.X - MinBounds.X) / 2.0.
- θ = half the camera’s Field of View
- a (adjacent) = how far back the camera needs to be.
Remembering our trig:
tan(θ) = o / a. Solving for a, we get:
a = o / tan(θ).
Now, if you’re using the default camera FoV of 90°, this becomes easy because tan(45°) is 1. In this case, a = o! Done!
But lets say your max - min bounds on the horizontal axis is 300, and your camera angle is, oh, 75°. That gives us a = 150 / tan(37.5°), or ~195.49.
Hopefully that’s enough to get you started. Some other things to consider are:
- you may want to pad the bounds by a little bit, so your players aren’t at the very edge of the camera.
- you may want to set a minimum camera distance, so when the players are close together the camera doesn’t zoom in uncomfortably close.
- you’ll probably want to use this math to calculate the camera position each frame, and then VInterpTo between the previous location and the new location to keep the camera smooth.
- If you want to keep the camera at a fixed distance and just change the zoom (fov), you simply rearrange the above equation to solve for the angle (so,
θ = atan(o/a)).
- If you have to worry about players moving up high or down low, you’ll also need to take into account the vertical axis. You’ll solve the same triangle, but o = half the vertical bounds, and θ = half the vertical FoV. The vertical FoV can be calculated by taking the camera FoV and dividing it by the camera Aspect Ratio. You’ll solve both triangles and position the camera based on the larger of the two distances.