xxxxxxxxxx
72
let canvas;
let pos = {
x: 0,
y: 0
};
let speed = {
x: 2,
y: 1
};
let ball;
class Ball {
// our class definition
constructor() {
// initialize stuff
this.x = random(100, width-100);
this.y = random(100, height-100);
this.speedX = random(-10, 10);
this.speedY = random(-10, 10);
this.d = random(20, 100);
this.ballColor = 255;
}
draw() {
fill(this.ballColor);
circle(this.x, this.y, this.d);
}
update() {
this.x = this.x + this.speedX;
this.y = this.y + this.speedY;
if (this.atHorizontalWall()) {
this.speedX = -this.speedX;
}
if (this.atVerticalWall()) {
this.speedY = -this.speedY;
}
}
atHorizontalWall() {
return this.x > width - this.d/2 || this.x < this.d/2;
}
atVerticalWall() {
return this.y > height - this.d/2 || this.y < this.d/2;
}
}
function setup() {
canvas = createCanvas(200, 200);
speed.x = random(-5, 5);
speed.y = random(-5, 5);
ball = new Ball();
}
function draw() {
background(220);
ball.draw();
ball.update();
canvas.position(pos.x, pos.y);
pos.x += speed.x;
pos.y += speed.y;
if (pos.x < 0 || pos.x > windowWidth - width) {
speed.x = -speed.x;
}
if (pos.y < 0 || pos.y > windowHeight - height) {
speed.y = -speed.y;
}
}