Object mouse interaction - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki

When creating interactive applications we can work at different levels of abstraction. p5.js provides one of the lowest levels of abstraction in that we are responsible for the pixels themselves by drawing onto a canvas. Other authoring environments, like the now defunct Adobe Flash were object-oriented in that objects were inserted onto the scene and could be repositioned and even have events associated with them. HTML is also object-oriented through interaction with the DOM (Document Object Model).

So p5.js is quite primitive in the functionality it provides, and we are required to write more code to handle the lack of object-oriented features.

One particular use case which is quite common in interactive applications is simply being able to interact with an onscreen object. p5.js doesn't have a concept of an onscreen object, instead the operations of drawing to the screen and handling input are two very distinct and independent tasks. We need to be able to combine them together.

To do this we need to be able to know (i.e. record, or keep a copy) of the object's location and overall size, and check if we have interacted with it every time there is a mouse event.

We are currently storing the location of our targets, however we aren't recording their size. In this case it doesn't matter top much because we know their size.

To detect if a target is clicked we need to check all of the targets in the mouse clicked handler:

function mouseClicked() {
  for (var i = 0; i < targetX.length; i++) {
    if (mouseX > targetX[i] - 20 && mouseX < targetX[i] + 20 && mouseY > targetY[i] - 20 && mouseY < targetY[i] + 20) {
      // Clicked
    }
  }
}

Note: we need to - 20 and + 20 as the ellipse are drawn centred.