Lesson 7.4

Mouse Interaction with Objects

Watch: Mouse Interaction with Objects - p5.js Tutorial

Video for 7.4:

To have an object respond to a mouse event, we will call a function within mousePressed() or mouseDragged().

Example 7.4.1 : Create 5 balls as in exercise 7.4b. Include a property for the radius, r. Add a method, clicked(), which turns the ball clicked green.

We start by including radius, r, as a parameter for the constructor function..

To have the display of the circle dependent on the radius we define it as follows:

Our clicked() method uses the arguments passed to it for the location of the mouse when clicked, x, and y, and uses them calculate the distance from the center of the ball. If the distance is less than the radius of the ball it turns the ball green.

This method is called by mousePressed() for each ball when the mouse is clicked.

Example 7.4.1

Exercise 7.4a: Use the patch class from 7.3d-f, to cover the canvas with rectangles of varying colors. When the user clicks on a grey rectangle it should turn red. When the user drags the mouse across any of the rectangles they should turn green.