Sign in to follow this  

2D zooming to cursor [SOLVED]

Recommended Posts

I'm stumped by this. I've tried googling this up, to no avail. I'm working on a Master of Orion-esque game, and I got starlanes working. (See here.) Now my problem is zooming. I can zoom out and the game will zoom out centered on my current view. Zooming is achieved by scaling the star sprites to be bigger or smaller, and drawing them in correct positions. However, when I zoom in, I want the map to zoom in where my mouse cursor is. I've noticed this effect in Sins of Solar Empire. I've managed to find the grid cell where the cursor is hovering over. But how to zoom in the map with that grid cell still in the same position? This is my code:
//find the grid cell the mouse is hovering above
int zoomX = (int)((float)mouseX / incrementsX);
int zoomY = (int)((float)mouseY / incrementsY);

cameraX = (int)((float)zoomX / (float)zoomSize) * (zoomSize - 3) - zoomSize;
cameraY = (int)((float)zoomY / (float)zoomSize) * (zoomSize - 3) - zoomSize;

zoomSize is the current size of the grid visible. For example, 20x20 is visible out of 100x100 grid, and when I zoom out, now it is 25x25 visible. incrementsX and Y are the size of individual cells in width and height based on zoomSize and the window resolution. ZoomX and Y is the cell to be zoomed toward cameraX and Y is the top left cell of the zoomSize. I tried to take the percentage position (i.e. 65% to the right) and applying it to the new zoomed size, but it resulted in random movements. I'm stuck on this :( Any help will be really appreciated! [Edited by - Zeraan on December 29, 2009 1:10:36 AM]

Share this post

Link to post
Share on other sites
I solved it! I realized that I wasn't including the original camera coordinates, and I just need to calculate the new offset. In case you're curious on how it works, here's the code

//find the grid cell the mouse is hovering above
int offsetX = (int)((float)mouseX / incrementsX);
int offsetY = (int)((float)mouseY / incrementsY);

int newOffsetX = (int)(((float)offsetX / (float)zoomSize) * (zoomSize - 5));
int newOffsetY = (int)(((float)offsetY / (float)zoomSize) * (zoomSize - 5));

cameraX += offsetX - newOffsetX;
cameraY += offsetY - newOffsetY;

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this