xxxxxxxxxx
106
let numBalls = 10;
let x;
let y;
let speedX = 3;
let speedY = 5;
let d = 50;
let bg = {
r: 255,
g: 0,
b: 0
}
let balls = [];
function clearCanvas(r, g, b) {
background(r, g, b);
}
function drawBall(x, y, d, ballColor) {
fill(ballColor);
circle(x, y, d);
}
function drawBalls() {
for (let i = 0; i < balls.length; i+=1) {
let x = balls[i].x;
let y = balls[i].y;
let d = balls[i].d;
drawBall(x, y, d, 255);
}
}
function initializeBalls() {
for (let i = 0; i < numBalls; i+=1) {
balls[i] = initializeBall();
}
}
function initializeBall() {
return {
x: random(100, width-100),
y: random(100, height-100),
speedX: random(-10, 10),
speedY: random(-10, 10),
d: random(20, 100)
}
}
function updateBall(ball) {
ball.x = ball.x + ball.speedX;
ball.y = ball.y + ball.speedY;
if (ballAtHorizontalWall(ball)) {
ball.speedX = -ball.speedX;
}
if (ballAtVerticalWall(ball)) {
ball.speedY = -ball.speedY;
}
}
function updateBalls() {
for (let i = 0; i < numBalls; i+=1) {
updateBall(balls[i]);
}
}
function ballAtHorizontalWall(ball) {
return ball.x > width - ball.d/2 || ball.x < ball.d/2;
}
function ballAtVerticalWall(ball) {
return ball.y > height - ball.d/2 || ball.y < ball.d/2;
}
function mousePressed() {
bg = randomColor();
}
function randomColor() {
return {
r: random(0, 255),
g: random(0, 555),
b: random(0, 255)
};
}
function setup() {
createCanvas(400, 400);
initializeBalls();
}
function draw() {
// clearing the canvas
clearCanvas(bg.r, bg.g, bg.b);
// drawing
drawBalls();
updateBalls();
}