class Ball {
// …
onCollide({ x, y }) {
if (x) {
this.vel.x = -this.vel.x;
}
if (y) {
this.vel.y = -this.vel.y;
}
}
}Bounce off the walls / notebook
Bounce off the walls
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
const x = hittingLeftBoundary || hittingRightBoundary;
const y = hittingTopBoundary || hittingBottomBoundary;
if (x || y) {
ball.onCollide({ x, y });
}const hittingLeftBoundary = ball.pos.x - ball.size.w / 2 <= 0 && ball.vel.x < 0;class Ball {
// …
get hitbox() {
return {
left: this.pos.x - this.size.w / 2,
right: this.pos.x + this.size.w / 2,
top: this.pos.y - this.size.h / 2,
bottom: this.pos.y + this.size.h / 2,
};
}
}function handleWallCollisions(object, width, height) {
const hitbox = object.hitbox;
const hittingLeftBoundary = hitbox.left <= 0 && object.vel.x < 0;
const hittingRightBoundary = hitbox.right >= width && object.vel.x > 0;
const hittingTopBoundary = hitbox.top <= 0 && object.vel.y < 0;
const hittingBottomBoundary = hitbox.bottom >= height && object.vel.y > 0;
const x = hittingLeftBoundary || hittingRightBoundary;
const y = hittingTopBoundary || hittingBottomBoundary;
if (x || y) {
object.onCollide({ x, y });
}
}ball.move(dt);
handleWallCollisions(ball, canvas.width, canvas.height);