xxxxxxxxxx
117
// 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 right & left walls
// if (xPos <=0 || xPos >= width) {
// xSpeed = -xSpeed;
// }
// if (yPos <=0 || yPos >= height) {
// ySpeed = -ySpeed;
// }
// circle(xPos, yPos, 30);
// }
// OBJECT ORIENTED PROGRAMMING
// let ball;
// function setup() {
// createCanvas(400, 400);
// ball = new BouncingBall();
// }
// function draw() {
// background(50, 89, 100);
// ball.move();
// ball.checkforCollisions();
// ball.draw();
// }
// class BouncingBall {
// constructor() {
// this.xPos = width/2;
// this.yPos = random (100, 300);
// this.xSpeed = 4;
// this.ySpeed = 7;
// }
// move() {
// this.xPos += this.xSpeed;
// this.yPos += this.ySpeed;
// }
// checkforCollisions() {
// if (this.xPos <=0 || this.xPos >= width) {
// this.xSpeed = -this.xSpeed;
// }
// if (this.yPos <=0 || this.yPos >= height) {
// this.ySpeed = -this.ySpeed;
// }
// }
// draw(){
// circle(this.xPos, this.yPos, 30);
// }
// }
// OBJECT ORIENTED PROGRAMMING with arguments
let ball;
function setup() {
createCanvas(400, 400);
ball = new BouncingBall(30, 20, 4, 7);
}
function draw() {
background(50, 89, 100);
ball.move();
ball.checkforCollisions();
ball.draw();
}
class BouncingBall {
constructor(xPos, yPos, xSpeed, ySpeed) {
this.xPos = xPos;
this.yPos = yPos;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
}
move() {
this.xPos += this.xSpeed;
this.yPos += this.ySpeed;
}
checkforCollisions() {
if (this.xPos <=0 || this.xPos >= width) {
this.xSpeed = -this.xSpeed;
}
if (this.yPos <=0 || this.yPos >= height) {
this.ySpeed = -this.ySpeed;
}
}
draw(){
circle(this.xPos, this.yPos, 30);
}
}