在2D坐标中缩放到屏幕的中心

C++ Zoom into the centre of the screen in 2D coordinates

本文关键字:屏幕 缩放 2D 坐标      更新时间:2023-10-16

我很难做出正确的计算,以便在2D坐标中放大屏幕中心,同时保持所有内容的正确比例。

我有一个矢量,我用它来处理周围移动我的地图编辑器如下:

scroll = sf::Vector2<float>(-640.0f, -360.0f);

设置为-640.0f, -360.0f,使0,0在初始化时屏幕的中心(基于我的窗口是1280x720)。

我的缩放值范围从0.1f到2.0f,它以0.05的增量增加或减少:

zoomScale = zoomScale + 0.05;

在屏幕上绘制元素时,使用以下代码绘制:

sf::Rect<float> dRect;
dRect.left = (mapSeg[i]->position.x - scroll.x) * (layerScales[l] * zoomScale);
dRect.top = (mapSeg[i]->position.y - scroll.y) * (layerScales[l] * zoomScale);
dRect.width = (float)segDef[mapSeg[i]->segmentIndex]->width;
dRect.height = (float)segDef[mapSeg[i]->segmentIndex]->height;
sf::Sprite segSprite;
segSprite.setTexture(segDef[mapSeg[i]->segmentIndex]->tex);
segSprite.setPosition(dRect.left, dRect.top);
segSprite.setScale((layerScales[l] * zoomScale), (layerScales[l] * zoomScale));
segSprite.setOrigin(segDef[mapSeg[i]->segmentIndex]->width / 2, segDef[mapSeg[i]->segmentIndex]->height / 2);
segSprite.setRotation(mapSeg[i]->rotation);
Window.draw(segSprite);

layerScales是一个值,用于缩放视差滚动的分段层。

当放大和缩小时,这似乎工作得很好,但中心点似乎发生了变化(我知道一个元素应该总是在0,0将位于不同的坐标,只要我放大)。我使用以下代码来计算鼠标的位置,以测试如下所示:

mosPosX = ((float)input.mousePos.x + scroll.x) / zoomScale)
mosPosY = ((float)input.mousePos.y + scroll.y) / zoomScale)

我确信我应该对"滚动"矢量做一个计算,以考虑到这个缩放,但我似乎不能让它正确工作。

我试着实现下面的东西,但它没有产生正确的结果:

scroll.x = (scroll.x - (SCREEN_WIDTH / 2)) * zoomScale - (scroll.x - (SCREEN_WIDTH / 2));
scroll.y = (scroll.y - (SCREEN_HEIGHT / 2)) * zoomScale - (scroll.y - (SCREEN_HEIGHT / 2));

你知道我做错了什么吗?

我将采用简单的方法(不是最有效的,但效果很好),并且只适用于单轴(第二个也是一样的)

最好设置为未缩放的偏移量:

scaledpos = (unscaledpos*zoomscale)+scrolloffset

知道标尺变化后中心点不应移动(0表示前,1表示后):

scaledpos0 == scaledpos1

所以这样做:

scaledpos0 = (midpointpos*zoomscale0)+scrolloffset0; // old scale
scaledpos1 = (midpointpos*zoomscale1)+scrolloffset0; // change zoom only
scrolloffset1+=scaledpos0-scaledpos1;                  // correct offset so midpoint stays where is ... i usualy use mouse coordinate instead of midpoint so i zoom where the mouse is 

当你不能改变比例方程的时候,就对你的

做同样的事情
scaledpos0 = (midpointpos+scrolloffset0)*zoomscale0;
scaledpos1 = (midpointpos+scrolloffset0)*zoomscale1;
scrolloffset1+=(scaledpos0-scaledpos1)/zoomscale1;

希望我没有在那里犯愚蠢的错误(从记忆中写)。更多信息请参见

  • 基于当前鼠标位置缩放图形