How to ZoomIn/ZoomOut of a 2D world while keeping the clicked point visible?

Started by
1 comment, last by Ishaq 15 years, 9 months ago
Hello, How can I ZoomIn/ZoomOut in a 2D world (I am using orthographic projection) so that the clicked point (or the point that initiated the zoom always remains visible). e.g.

-------------------------
(0,0)....................|
|........................|
|........................|
|........................|
|........................|
|........................|
|........................|
|...............(799,599)|
|------------------------|
Say the user clicks at (0,0) and zooms in 3x, how should I keep 0,0 at the top left corner of the visible screen. Also, say user has already zoomed in the world at 10x, and clicks (799, 599) and zooms out to 0.5x, so how should I do that after being zoomed out at 0.5x, the world (half of the screen size now) appears in the center of the screen? Appreciate your help. Regards, MI PS: Although I am doing it in OpenGL, but I thought this post belongs here, I hope I was right.
Advertisement
If you want a given point on-screen to remain in the same place, relative to the screen, after a zoom change, what you want to do is find the world and on-screen positions of you want to track, make the zoom change, find the new world coordinate of the same on-screen position, and then move the view by the difference between the two world coordinates.

A source snippet from the event loop of my home-grown CAD application; getMouseLoc() calls glfwGetMousePos(&x, &y) and returns the 2D world coordinate under the cursor. A 3-dimension vector Float3 is used only because I didn't want to maintain multiple vector classes.
	// Zoom in or out with wheel movement.	int mouseWheel = glfwGetMouseWheel();	int mouseSign = sign(mouseWheel);	if ( mouseWheel != 0 )	{		Float3 preZoomCursor = getMouseLoc();		float preZoom = zoom;				zoom += log10(zoom) * 5 * mouseSign;		if ( zoom < 2 ) zoom = 2;		glfwSetMouseWheel(0);				// Maintain focus only when zooming in. Remove the 'if' to		// lock the focus position when zooming out as well, but this		// looks unintuitive to most people; it ends up zooming out and		// away from the focus point.		if ( zoom > preZoom )		{			cameraLoc += preZoomCursor - getMouseLoc();		}	}
RIP GameDev.net: launched 2 unusably-broken forum engines in as many years, and now has ceased operating as a forum at all, happy to remain naught but an advertising platform with an attached social media presense, headed by a staff who by their own admission have no idea what their userbase wants or expects.Here's to the good times; shame they exist in the past.
thanks, works like a charm :)

This topic is closed to new replies.

Advertisement