Tutorial :3D Camera Zoom and follow physics in java?



Question:

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?


Solution:1

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.


Solution:2

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.


Solution:3

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.


Solution:4

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);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »