Keeping two objects on the screen?

I’m trying to make it so that no matter how far apart two objects are they’ll both remain on screen.
This is what I got so far:

float distance = (float) ((Math.sqrt((p1.x - p2.x) + (p1.y - p2.y))));
float camx = (float)((p1.x + p2.x) * 0.5);
float camy = (float)((p1.y + p2.y) * 0.5);
float camz = (float) (distance * 5);

What is the math I need so the Z zooms in and out correctly?

One that should help is that distance should be:


float distance = (float) Math.sqrt( (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y) );

To calculate the distance needed, try this:


float width = Math.abs(p1.x - p2.x) + PADDING;
float camx = (float) ( (p1.x + p2.x) * .5);
float camy = (float) ( (p1.y + p2.y) * .5);

float camz = (float) (.5 * width * Math.tan(.5 * fov));

The only things I’ve added are PADDING (which would be a constant that just affects how much space between the edges of the screen you want), and the variable fov. fov is the field of view angle that you’re using when rendering. If you’re using JOGL, it’s one of the values used in gluPerspective(), probably 60 degrees.