放大至鼠标(例如Google地图) [英] Zoom toward mouse (eg. Google maps)

查看:131
本文介绍了放大至鼠标(例如Google地图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为2D策略游戏编写了home-brew view_port类.平移(使用箭头键)和缩放(使用鼠标滚轮)可以很好地工作,但是我希望视图也可以将 home 放到光标所在的位置,例如

I've written a home-brew view_port class for a 2D strategy game. The panning (with arrow keys) and zooming (with mouse wheel) work fine, but I'd like the view to also home towards wherever the cursor is placed, as in Google Maps or Supreme Commander

我将为您提供实现缩放的方式以及我使用的语言的详细信息:这都是无关紧要的.重要的是缩放功能,该功能可以修改表示视图的矩形结构(x,y,w,h).到目前为止,代码如下:

I'll spare you the specifics of how the zoom is implemented and even what language I'm using: this is all irrelevant. What's important is the zoom function, which modifies the rectangle structure (x,y,w,h) that represents the view. So far the code looks like this:

void zoom(float delta, float mouse_x, float mouse_y)
{
    zoom += delta;
    view.w = window.w/zoom;
    view.h = window.h/zoom;  
    // view.x = ???
    // view.y = ???
}

在有人建议之前,以下内容将不起作用:

Before somebody suggests it, the following will not work:

view.x = mouse_x - view.w/2;
view.y = mouse_y - view.h/2;

这张照片说明了为什么我尝试放大笑脸时的原因:

This picture illustrates why, as I attempt to zoom towards the smiley face:

如您所见,当鼠标下方的对象放置在屏幕中央时,它不再位于鼠标下方,因此我们不再朝其缩放!

As you can see when the object underneath the mouse is placed in the centre of the screen it stops being under the mouse, so we stop zooming towards it!

如果您精通数学(需要一个),那么在此方面的任何帮助将不胜感激!

If you've got a head for maths (you'll need one) any help on this would be most appreciated!

推荐答案

我设法弄清了解决方案,这要归功于很多小细节:如果有其他人,我将在此处发布该算法需要它.

I managed to figure out the solution, thanks to a lot of head-scratching a lot of little picture: I'll post the algorithm here in case anybody else needs it.

Vect2f mouse_true(mouse_position.x/zoom + view.x, mouse_position.y/zoom + view.y);
Vect2f mouse_relative(window_size.x/mouse_pos.x, window_size.y/mouse_pos.y);   
view.x = mouse_true.x - view.w/mouse_relative.x;
view.y = mouse_true.y - view.h/mouse_relative.y;

这可确保放置在鼠标下方的对象保持在鼠标下方.您可以在 github上查看代码,我还为 youtube 作了展示演示.

This ensures that objects placed under the mouse stay under the mouse. You can check out the code over on github, and I also made a showcase demo for youtube.

这篇关于放大至鼠标(例如Google地图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆