views:

326

answers:

4

I'm trying to make it so that no matter how far apart two objects are they'll both remain on screen. I'm using JOGL, but that shouldn't matter as I just need help with the math. This is what I have 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?

+2  A: 

Maybe I'm misunderstanding your situation, but couldn't you just do

float camx = (p1.x + p2.x) * 0.5;
float camy = (p1.y + p2.y) * 0.5;
float camz = (p1.z + p2.z) * 0.5;

That would position the camera directly between the two objects.

David Zaslavsky
This worked for X and Y, but not for Z. Thanks very much though.
William
That just means you're not actually trying to put the camera between the two objects. It'd probably help to edit some more detail into your question about what exactly you're trying to do.
David Zaslavsky
I'm trying to make it so that no matter how far apart some objects are they'll both remain on screen.
William
A camera placed perfectly between two points (in 3 dimensions) can't possibly see both of them at the same time - unless the field of view is greater than 180 degrees...
Charlie Tangora
Yeah, I thought it slightly odd that the question was asking how to position a camera directly between two points (although I see it's now been edited)
David Zaslavsky
+1  A: 

Should it need to be corrected as,

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

I am not prettey sure about the Syntax. I am just telling you need to get the power of 2 before adding vectors.

Chathuranga Chandrasekara
+3  A: 

If both objects have z=0, and your screen viewing angle (from the center of the screen to an edge) is ax and ay for the horizontal and vertical angles, then:

zx = abs((p1.x-p2.x)*0.5)/tan(ax)
zy = abs((p1.y-p2.y)*0.5)/tan(ay)

and

camz = max(zx, zy)

Here zx and zy are the distances to get the objects onto the horizontal and vertical dimensions of the screen, and camz is the distance that satisfies both criteria. Also note that ax and ay are in radians (for example, if you assume your screen is 40 deg wide, then ax is 20 deg, or ax =20*(pi/180)=0.3419 radians).

Your values for camx and camy were correct.

tom10
A: 
float distance = (float) ((Math.sqrt(Math.pow((p1.x - p2.x),2.0) + Math.pow((p1.y - p2.y), 2.0))));
float camx = (float)((p1.x + p2.x) * 0.5);
float camy = (float)((p1.y + p2.y) * 0.5);
float camz = (float) Math.abs(distance);
William