How do zoom relative to mouse?

Hi,

My sketch basically draws objects from left to right. I implemented a zoom function with the mouse wheel with translation but it doesn't zoom relative to my mouse.

Any ideas how to fix this?

float x = 100;
int y = 200;
int gap = 50;
float scale = 1.0;

ArrayList<Body> bodies = new ArrayList<Body>();

class Body {

  String name;
  int size;

  Body(String name, int size) {
    this.name = name;
    this.size = size;
  }

  float getSize() {
    return this.size * scale;
  }

  void draw(float x) {
    fill(255);
    noStroke();
    ellipse(x, y - this.getSize() / 2, this.getSize(), this.getSize());
    noFill();
    stroke(255,0,255);
    rect(x, y - this.getSize() / 2, this.getSize(), this.getSize());
  }
}

float getOffset() {
  int offset = 0;
  for (Body body : bodies) {
    offset += body.getSize();
    offset += gap;
  } 
  return offset;
}

void setup() {
  size(1600, 900);
  ellipseMode(CORNER);

  bodies.add(new Body("test", 100));
  bodies.add(new Body("2", 400));
  bodies.add(new Body("big", 1000));
}

void draw() {
  fill(0);
  noStroke();
  rect(0, 0, 1600, 900);

  pushMatrix();
  translate(x, y);

  float drawX = x;
  for (Body body : bodies) {
    body.draw(drawX);
    drawX += (body.getSize() + gap);
    fill(255,255,0);
    noStroke();
    rect(drawX - gap, y - gap / 2, gap, gap);
  }

  popMatrix();
}

void keyPressed() {
  float prevOffset = getOffset();
  if (keyCode == UP) {
    scale *= 1.1;
    float newOffset = getOffset();
    //x -= (newOffset - prevOffset) / 2;
    x -= mouseX * 0.1;
  } else if (keyCode == DOWN) {
    scale *= 0.9;
    float newOffset = getOffset();
    //x += (prevOffset - newOffset) / 2;
    x += mouseX * 0.1;
  } else if (keyCode == LEFT) {
    x += 10;
  } else if (keyCode == RIGHT) {
    x -= 10;
  }
  if (scale < 0) {
    scale = 0;
  }
}

void mouseWheel(MouseEvent event) {
  float e = event.getCount();
  if (e < 0) {
    scale *= 1.1;
  } else if (e > 0) {
    scale *= 0.9;
  }
  x -= event.getCount() * mouseX / 1000;
}

Answers

Sign In or Register to comment.