brennanenanen
brennanenanen

Reputation: 429

How to zoom into mouse position with correct translation

I'm trying to zoom a grid in Processing and I am having trouble with applying the correct translation such that zooming is centered around the mouse position. I have searched the web for a while but nothing I try seems to work.

The screen size is width and height and the mouse position is mouseX and mouseY.

The code I have at the moment is below, but it zooms the grid (controlled by player.zoom) from the top left corner which is not what I want. To update the translation of the grid, player has the 2d vector 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;
}

If you need more details to answer I can link the repo with the source code.

Upvotes: 0

Views: 203

Answers (1)

Luke Garrigan
Luke Garrigan

Reputation: 5011

I have created a very simple mock-up for you which will hopefully point you in the right direction into applying this to your player.

So this little demo shows the zooming in to the centre of an ellipse whilst keeping it as the central focus.

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;
  }
}

I suggest you to copy this into a new project and then comment out specific lines to try to understand what's going on and how you can transfer this over to your own project.

The same principles still apply, I didn't do this with mouse input in the effort of making the program as simple as possible.

Upvotes: 1

Related Questions