xxxxxxxxxx
95
const BALL_SPEED = 5;
const BALL_SIZE = 30;
const BALL_AGE = 1000;
const balls = [];
class Ball {
constructor(x, y, dir, col) {
this.pos = createVector(x, y);
this.vel = createVector(BALL_SPEED, BALL_SPEED);
this.vel.rotate(radians(dir));
this.col = col;
this.srk = [0, 0, 0, 150];
this.age = BALL_AGE;
}
draw() {
if (this.age <= BALL_AGE * 0.1) {
this.col = [
red(this.col),
green(this.col),
blue(this.col),
alpha(this.col) * 0.8
];
this.srk = [
red(this.srk),
green(this.srk),
blue(this.srk),
alpha(this.srk) * 0.8
]
}
push();
translate(this.pos.x, this.pos.y);
fill(this.col);
stroke(this.srk);
circle(0, 0, BALL_SIZE);
pop();
}
move() {
if (this.pos.x < 0) { // left border
let sn = createVector(BALL_SPEED, 0);
this.vel.reflect(sn);
} else if (this.pos.x > windowWidth) { // right border
let sn = createVector(-BALL_SPEED, 0);
this.vel.reflect(sn);
} else if (this.pos.y < 0) { // top border
let sn = createVector(0, BALL_SPEED);
this.vel.reflect(sn);
} else if (this.pos.y > windowHeight) { // bottom border
let sn = createVector(0, -BALL_SPEED);
this.vel.reflect(sn);
}
this.pos.add(this.vel);
}
run() {
this.age--;
if (this.age > 0) {
this.draw();
this.move();
}
}
}
function setup() {
createCanvas(windowWidth, windowHeight);
let col = [
random(0, 255),
random(0, 255),
random(0, 255),
150
];
let ball = new Ball(
random(10, windowWidth - 10),
random(10, windowHeight - 10),
random(0, 360),
col
);
balls.push(ball);
}
function draw() {
background("#B7EDFF");
balls.forEach(b => b.run());
}
function mouseDragged() {
let col = [
random(0, 255),
random(0, 255),
random(0, 255),
150
];
let b = new Ball(mouseX, mouseY, random(0, 360), col);
balls.push(b);
}