1

I'm trying to figure out how to detect in processing / processing js when the mouse is over a certain object on screen. In this case, I am drawing lines. It seems like processing can't attach a "listener" to an object, so I would have to do this with some sort of coordinate detection - but I haven't found any good examples of this. This is my code so far:

void draw() {
 for(int i = 0; i < commLength; i ++) { 
  ...
  line(circ.x, circ.y, circ.x + dir.x, circ.y + dir.y);
 }
}

void mouseOver(){
 //need to detect if mouse is over one of the lines.
}
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
mheavers
  • 29,530
  • 58
  • 194
  • 315

1 Answers1

3

The way I do this is to check if the mouse is within a certain distance from the start and the end of the line:

boolean mouseIsOverLine(float x1, float y1, float x2, float y2) {
  float d = dist(x1, y1, x2, y2);
  float d1 = dist(x1, y1, mouseX, mouseY);
  float d2 = dist(x2, y2, mouseX, mouseY);

  // distance between vertices must be similar to sum of distances from each vertex to mouse
  if (d1 + d2 < d + MOUSE_OVER_LINE_DISTANCE_THRESHOLD) {
    return true;
  }

  return false;
}

where the line goes from (x1, y1) to (x2, y2). This image roughly shows an example that would return false (red lines) and one that would return true (green lines), depending on the value of MOUSE_OVER_LINE_DISTANCE_THRESHOLD. The mouse coordinates are at the orange dots in each case.

enter image description here

sblair
  • 1,085
  • 2
  • 13
  • 22