首页 > 解决方案 > 如何通过正确的翻译放大鼠标位置

问题描述

我正在尝试在处理中缩放网格,但在应用正确的翻译时遇到问题,以便缩放以鼠标位置为中心。我已经在网上搜索了一段时间,但我尝试的任何方法似乎都不起作用。

屏幕大小为widthand height,鼠标位置为mouseXand mouseY

我目前拥有的代码如下,但它player.zoom从左上角缩放网格(由 控制),这不是我想要的。要更新网格的平移,player具有 2d 矢量player.translate

void mouseWheel(MouseEvent event) {
  float zoomFactor = 200.0f;

  float scroll = event.getCount();
  player.zoom -= scroll * player.zoom / zoomFactor;

  // player.translate.x += something;
  // player.translate.y += something;
}

如果您需要更多详细信息来回答,我可以将 repo 与源代码链接。

标签: javaprocessing

解决方案


我为您创建了一个非常简单的模型,希望它可以为您指明正确的方向,将其应用于您的播放器。

所以这个小演示展示了放大到椭圆的中心,同时保持它作为中心焦点。

float scale = 1;
// displacement left/right
float xPan = 720;
// displacement up/down
float yPan = 450;
boolean zoomIn = true;

void setup() {
  size(1440, 900);
}


void draw() {

  // allows us to zoom into the center of the screen rather than the corner
  translate(width/2, height/2);
  scale(scale);
  translate(-xPan, -yPan);
  background(200);

  // draws the ellipse in the center
  ellipse(width/2, height/2, 100, 100);

  // does the zooming
  if (zoomIn) {
    scale *= 1.01;
  }
}

我建议您将其复制到一个新项目中,然后注释掉特定行以尝试了解发生了什么以及如何将其转移到您自己的项目中。

同样的原则仍然适用,我没有用鼠标输入来做这个,以使程序尽可能简单。


推荐阅读