ClickThrough_mousePressed()

The following demo illustrates ‘click through’; depending on where you click in the green rectangle, mousePressed() will report either two or three rectangles since they are overlapped. Is there a way to trap only the click in the green rectangle and not report the others? Addendum: Original post edited to reflect solution.

let r = [];

class Rect {
  constructor(xpos, ypos, wide, ht, fillColor) {
    this.x = xpos;
    this.y = ypos;
    this.w = wide;
    this.h = ht;
    this.fillColor = fillColor;
  }

  display() {
    fill(this.fillColor);
    rect(this.x, this.y, this.w, this.h);
    fill(0);
    text("Click in here.", 160, 160, 90, 20);
  }
}

function setup() {
  createCanvas(710, 400);
  r[0] = new Rect(100, 100, 100, 200, color(255, 0, 0)); // Red id = 0
  r[1] = new Rect(200, 100, 100, 200, color(0, 0, 255)); // Blue id = 1
  r[2] = new Rect(150, 150, 100, 100, color(0, 255, 0)); // Green id = 2
}

function draw() {
  for (let i = 0; i < r.length; i++) {
    r[i].display();
  }
}

function mousePressed() {
  for (let i = r.length - 1; i > -1; i--) {
    if ((mouseX >= r[i].x) && (mouseX <= r[i].x + r[i].w) && (mouseY >= r[i].y) && (mouseY <= r[i].y + r[i].h)) {
      console.log("id = " + i + " : " + r[i].fillColor);
      return;
    }
  }
  console.log("====================");
}

clickThrough

1 Like

When you test the green rectangle first:
Say return; after console.log in the for loop to leave the function automatically after the first finding

I was testing from the bottom-up; the secret is to test from the top-down and bail out after the first hit. Thanks.

Revised mousePressed()

// test from top -> down not bottom -> up
function mousePressed() {
  for (let i = r.length - 1; i > -1; i--) {
    if ((mouseX >= r[i].x) && (mouseX <= r[i].x + r[i].w) && (mouseY >= r[i].y) && (mouseY <= r[i].y + r[i].h)) {
      console.log("id = " + i + " : " + r[i].fillColor);
      return; // stop after first hit
    }
  }
  console.log("====================");
}
1 Like