Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.

so far, all I have is the resizing but I now need to change the map position.

What I have: map x and y; map width and height; cursor x and y.

Any help would be most welcome.

share|improve this question

2 Answers 2

Assuming that your map x and map y mean the top left corner of the screen area over your map in map coordinates and map width and map height are the dimensions of your map at the actual zoom level again in map coordinates (not screen coordinates), first, calculate your zoom ratio:

zoom x = screen width / map width;

Let's assume the aspect ratio does not change: zoom x = zoom y = zoom; If you want to change the zoom to next zoom, first find the coords of the new screen over your map:

new map width = screen width / next zoom

new map height = screen height / next zoom

We need to find the change in both values and distribute these depending on the mouse position on the screen. If the mouse position would be in the exact center screen position, then this change would be evenly divided between the top-bottom and left-right sides. Since the mouse is at an arbitrary position, we need to find the ratios for the height and width changes for the sides.

Let's assume that the screen dimensions are screen max width and screen max height; The new coordinates of your screen (dimensions new map width, new map height) over your map are:

new map x = map x - (cursor x / screen max width * (new map width - map width))
new map y = map y - (cursor y / screen max height * (new map height - map height))

To convert any map coordinate to a screen coordinate:

screen x = map x * zoom

and to convert back:

map x = screen x / zoom
share|improve this answer

Or for people using XNA when the system is flipped.

First calculate the mouse cursor in the world. Since the mouse position system in XNA is flipped subtract the mouse Y from the height of the screen.

var mouseinWorld = new Vector2(
    (cursor.X * oldZoomLevel) - world.X, 
    ((cursor.Y - screen.Height) * oldZoomLevel) + world.Y));

Now change your zoomlevel.

Next is to calculate the new world location.

var newX = (cursor.X * newZoomLevel) - mouseinWorld.X;
var newY = mouseinWorld.Y - ((cursor.Y - screen.Height) * newZoomLevel)

Now update the world location with the newly calculated coordinates.

world = new Vector2(newX, newY)
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.