I'm working on a 2D fighting game (using SDL) much like the original Killer Instinct on SNES. I want the camera to keep both players an equal distance from the left and right sides of the viewport. When either player moves, the camera adjusts to keep this equal distance and both players in view, except for when both players are at either end of the stage, during which the camera remains still. Here is an example of how the original KI camera works: http://youtu.be/eFgfaP7f7Rs?t=8m22s
I will provide a diagram of what I am trying to achieve.
The red box is the viewport (camera) which slides over the background image file to display the portion of the stage the players are currently in.
Goal: Each frame the player positions are checked and an algorithm is used to calculate the src.x clipping position for the camera. The midpoint, I believe, in addition with the distance between the players can be used to calculate this value. The viewport width and image width are stored in memory and can also be used. If one player moves, the camera moves at the same velocity, and if both are moving in the same direction, the camera should double its velocity to keep up, all whilst keeping both player's distances from the left and right sides in sync.
Currently, I am using integer math for all positions. I specify the clipping width on the image file using configuration files, so for example, my current background is 768 pixels wide and I clip it to 425 pixels wide, which is displayed in the viewport. The fighters have basic acceleration and max velocity. I use a Camera class to logically represent its x value from 0 to the right edge. The camera's x position is subtracted from the player's x position before rendering. Before rendering the background, I add the camera's x value to the clipping x value (src.x).
I have tried many silly things such as using the ratios of the image and clipping widths to get weird x values. I've tried simply using the midpoint and modifying it with whatever I could think of using the distance, but no luck. I do have semi correct movement by setting the camera x position to the midpoint - (image width - clipping width). However this of course does not keep the players at equal distances.
I've been trying to figure this out for a while and it seems so simple, yet the solution continues to elude me (I'm probably exhausted at the moment). It is possible there are some strange architectural decisions in my code that are making this needlessly difficult. If someone could help me figure out an algorithm, that would be all I need. I can provide more information as needed.