Skip to content

Instantly share code, notes, and snippets.

@georgesb
Last active May 3, 2020 00:15
Show Gist options
  • Save georgesb/03dd7e42475e6f765773cb02eb3c8c33 to your computer and use it in GitHub Desktop.
Save georgesb/03dd7e42475e6f765773cb02eb3c8c33 to your computer and use it in GitHub Desktop.
Bounce in a Box (Object)
<script src="https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"></script>
<script src="https://cdn.jsdelivr.net/gh/georgesb/lib/drawGrid.js"></script>
<script src="script.js"></script>
let box1;
let ball1;
function setup() {
createCanvas(800, 600);
box1 = new Box(50, 50, 350, 300);
ball1 = new Ball(32, box1);
}
function draw() {
background(250);
stroke(0);
drawGrid();
ball1.update();
ball1.display();
box1.display();
}
class Ball {
constructor(d, b) {
this.d = d;
this.b = b;
this.x = random(b.getLeft()+d,b.getRight()-d);
this.y = random(b.getTop()+d,b.getBottom()-d);
this.radius = d / 2;
this.xSpeed = random(3, 7);
this.ySpeed = random(3, 7);
}
update() {
this.x += this.xSpeed;
this.y += this.ySpeed;
if ((this.x > this.b.getRight() - this.radius) || (this.x < this.b.getLeft() + this.radius)) {
this.xSpeed = this.xSpeed * -1;
}
if ((this.y > this.b.getBottom() - this.radius) || (this.y < this.b.getTop() + this.radius)) {
this.ySpeed = this.ySpeed * -1;
}
}
display() {
noStroke();
fill('red');
circle(this.x, this.y, this.d);
}
}
class Box {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
display() {
noFill();
stroke(0);
strokeWeight(5);
rect(this.x, this.y, this.w, this.h);
}
getLeft() {
return this.x;
}
getRight() {
return this.w + this.x;
}
getTop() {
return this.y;
}
getBottom() {
return this.h + this.y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment