Using the mouse position to zoom in on a map

camX and camY should be floats, not ints.

draw() should not translate by the mouse position. Instead, when you change the scale, you need to change camX and camY so that they move relative to the world-space position of the mouse.

I simplified draw() and updated mouseWheel() to make the changes:

int gridSize = 20;
float camX = 0;
float camY = 0;
float camScale = 1;
boolean w = false, a = false, s = false, d = false;

void setup() {
  size(800, 800);
}

void draw() {
  if(w) {camY -= 5;}
  if(s) {camY += 5;}
  if(a) {camX -= 5;}
  if(d) {camX += 5;}
    
  background(220);
  
  push();
  scale(camScale);
  translate(-camX, -camY);
  drawGrid();
  pop();
}

void drawGrid() {
  for(int i = 0; i < 50; i++) {
    for(int j = 0; j < 50; j++) {
      fill(255);
      square(i*gridSize, j*gridSize, gridSize);
    }
  }
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  if(e == 1) {e = 1/1.1;}
  if(e == -1) {e = 1.1;}
  float oldScale = camScale;
  if(camScale * e >= 0.2) {
    camScale *= e;
  } else {
    camScale = 0.2;
  }
  float worldX = camX + mouseX/oldScale;
  camX = worldX - mouseX/camScale;
  float worldY = camY + mouseY/oldScale;
  camY = worldY - mouseY/camScale;
}

void keyPressed() {
  if (key == 'w') {w = true;}
  if (key == 's') {s = true;}
  if (key == 'a') {a = true;}
  if (key == 'd') {d = true;}
}

void keyReleased() {
  if (key == 'w') {w = false;}
  if (key == 's') {s = false;}
  if (key == 'a') {a = false;}
  if (key == 'd') {d = false;}
}
2 Likes