then bounce on the ground. Function buttonPressed() is created to clear array whenever button is pressed. There however is not any button drawn. Please assist to draw button adn then when that button is pressed that canvas is cleared and arrau again created when mouse is dragged. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // sketch.js var balls = []; ///////////////////////////////////////////////
Below is Javascript code. It is creating canvas with array of particles (balls) that fall when mouse is dragged, and then bounce on the ground.
Function buttonPressed() is created to clear array whenever button is pressed. There however is not any button drawn. Please assist to draw button adn then when that button is pressed that canvas is cleared and arrau again created when mouse is dragged.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// sketch.js
var balls = [];
///////////////////////////////////////////////
function setup() {
createCanvas(600,400);
}
///////////////////////////////////////////////
function draw() {
background(0);
for (let i = 0; i < balls.length; i++) {
var gravity = createVector(0, 0.1); // this is force that is pulling ball down
// add friction so that ball does not infinitely bounces up and down
var friction = balls[i].velocity.copy(); // this is force that is slowing ball down
friction.mult(-1); // getting opposite force, opposite direction
friction.normalize(); // sets size of friction to 1
friction.mult(0.01); // tiny force of opposite direction
balls[i].applyForce(friction);
balls[i].applyForce(gravity);
balls[i].run();
}
}
///////////////////////////////////////////////
class Ball {
constructor(x, y){
this.velocity = new createVector(random(-3, 3), random(-3, 3));
this.location = new createVector(x, y);
this.acceleration = new createVector(0, 0);
this.size = random(10, 50);
}
run(){
this.draw();
this.move();
this.bounce();
}
draw(){
fill(125);
ellipse(this.location.x, this.location.y, this.size, this.size);
}
move(){
this.velocity.add(this.acceleration);
this.location.add(this.velocity);
this.acceleration.mult(0);
}
bounce(){
if (this.location.x > width-this.size/2) {
this.location.x = width-this.size/2;
this.velocity.x *= -1;
} else if (this.location.x < this.size/2) {
this.velocity.x *= -1;
this.location.x = this.size/2;
}
if (this.location.y > height-this.size/2) {
this.velocity.y *= -1;
this.location.y = height-this.size/2;
}
}
// accumulation of forces
applyForce(force) {
this.acceleration.add(force);
}
}
function mouseDragged() {
balls.push(new Ball(mouseX, mouseY));
}
function buttonPressed() {
balls = [];
}
Step by step
Solved in 3 steps with 2 images