Rain Simulator: In this example we show how to create falling objects using a class and changing the properties of a class instance using a button and custom methods.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/addons/p5.sound.min.js"></script>
<script src="drop.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body></html>
Create a Sketch.JS file
//create global variables
var rain = []; //create a global array to store created droplets
let speedBut; //create a global varibal for any buttons
function setup() {
createCanvas(640, 360); // set canvas size
speedBut = createButton('Increase Speed'); //create button
speedBut.position(10,10); //set button location x,y
speedBut.mousePressed(speed); //set event listner to button
}
function draw() {
background(0); //draw background black
displayRain(); //update the rain every frame
if (frameCount % 120 == 0) { // if the frameCount is divisible by 60, then a second has passed. it will stop at 0
makeRain(); //make some rain by running makeRain() function
}
}
//updates the position of the rain and displays
function displayRain(){
for(var i =0;i<rain.length;i++){
rain[i].move();
rain[i].display();
}
}
//creates a new instance of the drop and stores in an array
function makeRain(){
d = new drop();
rain.push(d);
}
//this function increases the speed of each drop when button pressed
function speed(){
for(var i =0;i<rain.length;i++){
rain[i].increaseSpeed();
}
}
drop.js - Class File
class drop {
constructor() {
//set up class properties
this.x = random(width);
this.y = 0;
this.diameter = 10;
this.speed = 10;
}
//this will move the drop down the canvas and relocate to top
//when it reaches the bottom of the screen.
move() {
if (this.y > height) {
this.x = random(width);
this.y = 0;
} else {
this.y += this.speed;
}
}
//update the colour and draw on canvas
display(){
fill(random(255), random(255),random(255)); //set colour
rect(this.x, this.y, this.diameter, this.diameter);
}
//increaes the speed of the rain drop
increaseSpeed(){
if(this.speed>0){
this.speed+=2
}
}
}