Interaction

In the previous lesson on interaction, we looked at environment events and values like mouseX, mouseY and mousePressed.

Today, we'll look at interacting with shapes on the canvas. This will create a way for users to click on specific shapes in our sketch to interact with them.

Collision

In order to determine if a user has clicked on a shape in our sketch, we have to know if the mouse is inside the shape when the mouse is clicked. This can be referred to as a collision.

Circle collision

We can use the dist() function to determine if the mouse is inside of a circle.

dist returns the overall distance between two points.

Since we know that the outside of a circle is always the same distance from it's center, we can determine if the mouse is inside the circle by calculating the distance between the mouse and the center of a circle and comparing it to the circle radius, or half the width.

var r, g, b; function draw(){ background(0); fill(r, g, b); ellipse(width/2, height/2, 200, 200); } function mousePressed() { var d = dist(mouseX, mouseY, width/2, height/2); if (d < 100) { r = random(0, 255); g = random(0, 255); b = random(0, 255); } }

Rect button

Using a rect as a button requires a different method.

The rectangle can be uneven, but because it has straight lines, we can test to see if the mouse position is inside or outside each of it's boundaries.

var r, g, b; var x = 100, y = 100, w = 200, h = 100; function draw(){ background("black"); fill(r, g, b); rect(x, y, w, h); } function mousePressed() { if ( mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h ) { r = random(0, 255); g = random(0, 255); b = random(0, 255); } }

Using a button

The previous two buttons change their own color, but this isn't really the point of a button. A button should change appearance when it is clicked, but it should also perform some task.

The following example will draw a new random circle for every button click.

var r, g, b; var x = 100, y = 100, w = 200, h = 100; function draw(){ rect(x, y, w, h); } function mousePressed() { if ( mouseX > x && mouseX < x + w && mouseY > y && mouseY < y + h ) { r = random(0, 255); g = random(0, 255); b = random(0, 255); fill(r, g, b); ellipse(random(width), random(height), random(20, 100)); } }

What else could a button be used for?