Mouse Interaction with Objects

Resources:

Shiffman - 7.4: Mouse Interaction with Objects - p5.js

Simple Interaction

Let's forget about arrays for a moment and look at how we'll implement mouse events on a single object. We'll start by making a clicked() method within the Spot class. We already know the Spot's center x and y coordinate and radius. We also know the user's mouseX and mouseY. So all we need to do is check if when the mouse is clicked, is it less than one radius away from the Spot center point?

A useful shortcut for determining this is the dist() function, which returns the distance in pixels between two points. The syntax is:
dist(x1, y1, x2, y2);

Great, we made a clicked() method, but it's not doing anything yet. That's because we're not calling it. We call the move(), display() and bounce() methods once per frame in the draw() function. Is that where we want to call the click() function from? Probably not, because we only want to call that function when the mouse is clicked. Therefore, we'd want to use a standard mouseClicked() function (one of p5's native interrupt functions) and invoke (call) that method from there.

Now, instead of jsut printing a message to the console, let's create a visual indication that our Spot was clicked. Try changing the fill color within the clicked() function. Then, modify the code to create an array of 5 Spots moving at random speeds.

Solution below. See if you can modify the code below to create an array of rectangular images instead of circular Spots. You'll need to preload() the images, and do a bit more math than just dist() to determine if the click was inside the shape.

What if instead of a clicked() function, we had created a more general contains(x, y) function that accepted coordinates as parameters? This would make our Spot object more reusable, as we could recycle that method to be used not just for mouse interaction, but for interaction with other objects as well.