Week 9: March 25: Object mouse Events


    • Check out/review Organisms
    • Mouse Events with Classes
    • Dist
    • Perlin Noise
    • Look at Data Sets
    • Accessing Data from Array
    • Accessing Data from a CSV file
    • Studio Time


Using a mousePressed event with a Class

Variable Custom Shape

Basic Car with Class and mousePressed


In order to calculate whether we are over something or not, we need to measure the distance between where the mouse is and where the object is. We can use the dist() function to help with this.

Calculates the distance between two points.

dist(x1, y1, x2, y2)

x1 and y1 are the first points, and x2 and y2 are the second. Since we can use the position of mouseX and mouseY to figure out where the mouse is, we just need to know the location of the object. Since our class is stored in the this.x and this.y, we can use these attributes to check the distance. But let’s look at a simpler example first.

Distance Example Basic

Now what if we want to check the distance between the mouse and an object inside a class. We need to create a function inside the class to see if the mouse is over the object.

Basic Object + Distance Example

Okay, this works. But what if we have a ton of objects? Same principle, that we need to initialize the check of the distance for the object inside the for loop.

Multiple Objects + Dist

These objects change speed and color based on if the mouse hovers above them.

One last one that combines mousePressed + Dist hovers + classes


This tutorial from Dan Shiffman also shows how to use a mousePressed event with a class

Using keyPressed event with a Class

Basic Class + keyPressed

Perlin Noise / noise()

So far, we’ve been using random() to create and generate random values.

There is a different method that creates a smoother change between values. This is using the noise() function. This function is based on the concept of Perlin noise, which randomly assigns values in close proximity to each other, rather than large scale jumps. It was originally used for the procedural generation of graphics in the film Tron by Ken Perlin.Image result for original tron gif

This method works by randomly selecting a value between zero and one. We will use an offset to cycle through these values, and use the map function to resize the scale from zero to one to whatever it is that we are designing.

In the example below with the slider, the higher the value of the offset, the more dynamic the change, and closer to the likeness of random. The smaller the value, the changes in values are closer together and the animation appears smoother.

Perlin Noise Example

Perlin Noise with Slider