The Math
Welcome back!
Now that you know how to smoothly control the position and movement speed of the camera based on 2 points on a layout, lets proceed further.
For the pan and zoom, we primarily need to do 2 things:
1. Camera Position: Identify the center of all active objects on the layout.
2. Camera Zoom: Identify the distance between these active objects. If the distance is less, the camera can zoom in. If it's more, the camera needs to zoom out.
Here active objects can be players, enemies, powerups, levers/switches etc.
Now, there could be many such objects in a layout and doing these calculations for all of them can be very time consuming. This might lead to drop in your fps and a bad gaming experience. So, how do we do it smarter?
OK, we can do that by understanding that no matter how many such objects exist on the layout, there can only be a max of 4 objects at any given time that have the min X, min Y, max X and max Y values. Essentially these X,Y values form a rectangle that encapsulates all other objects.
See below image to visualize this.
As you can see above, there are 4 active objects (A,B,C & D). Of these 3 objects (A,B & C) form the edges of a rectangle that encapsulates all 4 objects.
As you can imagine, even if we had more than four active objects (say 100), the maximum number of objects that you need to worry about is 4. In the above example, we can get the coordinates of the rectangle with just 3 objects!
The green circle is the center of this rectangle and the X,Y coordinates for the same are calculated as shown in the image.
Now, let’s say these active objects move as depicted in the image below:
As you can see above, when the objects moved, two things happened:
1. The center of the rectangle moved
2. The rectangle changed size
Thus, using this rectangle you can do the following:
1. Camera Position: Position the camera on the center of the rectangle!
2. Camera Zoom: Make the zoom level proportional to the area of the rectangle!
Great! Now, lets move on to the implementation...