简体   繁体   中英

Zooming into the mouse, factoring in a camera translation? (OpenGL)

Here is my issue, I have a scale point, which is the unprojected mouse position. I also have a "camera which basically translates all objects by X and Y. What I want to do is achieve zooming into mouse position.

I'v tried this:

   1. Find the mouse's x and y coordinates 
   2. Translate by (x,y,0) to put the origin at those coordinates
   3. Scale by your desired vector (i,j,k)
   4. Translate by (-x,-y,0) to put the origin back at the top left

But this doesn't factor in a translation for the camera.

How can I properly do this. Thanks

glTranslatef(controls.MainGlFrame.GetCameraX(),
    controls.MainGlFrame.GetCameraY(),0);
glTranslatef(current.ScalePoint.x,current.ScalePoint.y,0);

glScalef(current.ScaleFactor,current.ScaleFactor,0);
glTranslatef(-current.ScalePoint.x,-current.ScalePoint.y,0);

Instead of using glTranslate to move all the objects, you should try glOrtho . It takes as parameters the wanted left coords, right coords, bottom coords, top coords, and min/max depth.

For example if you call glOrtho(-5, 5, -2, 2, ...); your screen will show all the points whose coords are inside a rectangle going from (-5,2) to (5,-2). The advantage is that you can easily adjust the zoom level.

If you don't multiply by any view/projection matrix (which I assume is the case), the default screen coords range from (-1,1) to (1,-1).

But in your project it can be very useful to control the camera. Call this before you draw any object instead of your glTranslate:

float left = cameraX - zoomLevel * 2;
float right = cameraX + zoomLevel * 2;
float top = cameraY + zoomLevel * 2;
float bottom = cameraY - zoomLevel * 2;
glOrtho(left, right, bottom, top, -1.f, 1.f);

Note that cameraX and cameraY now represent the center of the screen.

Now when you zoom on a point, you simply have to do something like this:

cameraX += (cameraX - screenX) * 0.5f;
cameraY += (cameraY - screenY) * 0.5f;
zoomLevel += 0.5f;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM