xxxxxxxxxx
69
let ballImage;
let balls = [];
let ballCount = 20;
const gravity = 0.1;
function preload() {
ballImage = loadImage("ball.PNG");
}
function setup() {
createCanvas(windowWidth, 500);
// .loop to add balls with random arguments...
for (let i = 0; i < ballCount; i++) {
console.log("making ball number "+i);
//create objects in an array
balls[i] = new Ball(
random(10, width - 10),// random x
random(0, 150),// random y
random(0.5, 0.95)// random bounce
);
}
}
function draw() {
background(220);
for (let i = 0; i < balls.length; i++) {
balls[i].show();
balls[i].move();
}
}
class Ball {
//requires "ballImage"
//requires constant "gravity"
constructor(_x, _y, _b) {
this.x = _x; //starting x position of bouncing ball
this.y = _y; //starting y position of bouncing ball
this.bounce = _b; //bounciness parameter
this.speed = 0;//initial speed
this.rotate = random(0, 100);//initial rotation position
}
show() {
push();
translate(this.x, this.y);
rotate(this.rotate / 60);
// line(-100, 0, 100, 0); // draws x axis so you can see rotation and translation
// line(0, -100, 0, 100); // draws y axis so you can see rotation and translation
imageMode(CENTER);
image(ballImage, 0, 0, 40, 40);
pop();
this.rotate++;
}
move() {
//bouncing move
this.y = this.y + this.speed;
this.speed += gravity;
if (this.y > height - 10) {
this.y = height - 10;
this.speed = -1 * this.bounce * this.speed; //reverse speed
}
}
}