Les 12 (optioneel) - classes
Hier de presentatie van de optionele les van 11 december:
En hieronder de code uit de les:
let ballen = [];
let aantal = 5;
let totalBounces = 0;
function setup() {
//plaats hier de code die maar ÊÊn keer hoeft te worden uitgevoerd
createCanvas(windowWidth,windowHeight);
background(255);
for (let i = 0 ; i < aantal; i++) {
ballen.push(new Ball());
}
console.log(ballen);
}
function draw() {
//plaats hier de code die continue herhaald moet worden.
background(0,10);
for (let i = 0 ; i < ballen.length; i++) {
ballen[i].teken();
ballen[i].move();
ballen[i].bounce();
}
if (totalBounces >= 1) {
ballen.push(new Ball());
totalBounces = 0;
}
}
function mousePressed() {
ballen.push(new Ball(mouseX,mouseY));
console.log(ballen);
}
class Ball {
constructor(x,y) {
this.s = random(20,50);
this.x = x || random(this.s/2,width-(this.s/2));
this.y = y || random(this.s/2,height-(this.s/2));
this.xSpeed = random(-4,4);
this.ySpeed = random(-4,4);
this.color = color(random(256),random(256),random(256));
this.bounceAmount = 0;
}
teken() {
fill(this.color);
stroke(this.color);
ellipse(this.x,this.y,this.s);
}
move() {
this.x += this.xSpeed;
this.y += this.ySpeed;
}
bounce() {
if (this.x < (this.s/2) || this.x > width-(this.s/2)) {
this.xSpeed *= 1.2;
this.xSpeed *= -1;
this.bounceAmount++;
totalBounces++;
}
if (this.y < (this.s/2) || this.y > height-(this.s/2)) {
this.ySpeed *= 1.1;
this.ySpeed *= -1;
this.bounceAmount++;
totalBounces++;
}
if (this.bounceAmount > 5) {
this.delete();
}
}
delete() {
let bosput = ballen.indexOf(this);
ballen.splice(bosput,1);
}
}