xxxxxxxxxx
123
// let xPos, yPos, xSpeed, ySpeed
// function setup() {
// createCanvas(400, 400);
// xPos = width/2;
// yPos = random(100,300);
// xSpeed = 4;
// ySpeed = 7;
// }
// function draw() {
// background(220);
// //move the ball
// xPos += xSpeed;
// yPos += ySpeed
// // check for collisions
// // check first for left and right wall
// if(xPos <=0 || xPos >= width) // if true, then reverse direction
// xSpeed = xSpeed * -1; // or xSpeed *= -1 or xSpeed = -xSpeed;
// // do same for cieling and floor
// if(yPos <=0 || yPos >= height) // if true, then reverse direction
// ySpeed = xSpeed * -1;
// circle(xPos, yPos, 50)
// }
// let xPos, yPos, xSpeed, ySpeed;
// function setup() {
// createCanvas(400, 400);
// xPos = width / 2;
// yPos = random(100, 300);
// xSpeed = 4;
// ySpeed = 7;
// }
// function draw() {
// background(220);
// // move the ball
// xPos += xSpeed;
// yPos += ySpeed;
// // check for collisions
// // check first for left and right wall
// if (xPos <= 15 || xPos >= (width-15)) {
// xSpeed = -xSpeed;
// }
// // do the same for the ceiling and the floor
// if (yPos <= 15 || yPos >= (height-15)) {
// ySpeed = -ySpeed;
// }
// circle(xPos, yPos, 30);
// }
class BouncingBall {
constructor(xSpeed0, ySpeed0) { //initial speed
this.xPos = width / 2;
this.yPos = random(100, 300);
this.xSpeed = xSpeed0;
this.ySpeed = ySpeed0;
}
move() {
// move the ball
this.xPos += this.xSpeed;
this.yPos += this.ySpeed;
}
checkForCollisions() {
// check first for left and right wall
if (this.xPos <= 15 || this.xPos >= width - 15) {
this.xSpeed = -this.xSpeed;
}
// do the same for the ceiling and the floor
if (this.yPos <= 15 || this.yPos >= height - 15) {
this.ySpeed = -this.ySpeed;
}
}
draw() {
circle(this.xPos, this.yPos, 30);
}
}
let myBouncingBall;
let ball2;
function setup() {
createCanvas(400, 400);
myBouncingBall = new BouncingBall(2, 2);
ball2 = new BouncingBall(10,10);
}
function draw() {
background(240);
myBouncingBall.move();
myBouncingBall.checkForCollisions();
myBouncingBall.draw();
ball2.move();
ball2.checkForCollisions();
ball2.draw();
}