xxxxxxxxxx
62
let pos = {
x: 25,
y: 100
};
let speed;
let ballSize = 50;
function setup() {
createCanvas(400, 400);
background(220);
initializeSpeed();
}
function draw() {
clearCanvas();
drawBall();
updatePosition();
updateSpeed();
}
function initializeSpeed() {
speed = {
x: random(-10, 10),
y: random(-10, 10)
};
}
function drawBall() {
ellipse(pos.x, pos.y, ballSize, ballSize);
}
function clearCanvas() {
background(220);
}
function updatePosition() {
pos.x = pos.x + speed.x;
pos.y = pos.y + speed.y;
}
function ballAtVertWall() {
let ballAtRightWall = pos.x > width - ballSize/2;
let ballAtLeftWall = pos.x < ballSize/2;
return ballAtRightWall || ballAtLeftWall;
}
function ballAtHorzWall() {
let ballAtBottomWall = pos.y < ballSize/2;
let ballAtTopWall = pos.y > height - ballSize/2;
return ballAtBottomWall || ballAtTopWall;
}
function updateSpeed() {
if (ballAtVertWall()) {
speed.x = -speed.x;
}
if (ballAtHorzWall()) {
speed.y = -speed.y;
}
}