// ball // James Brink, 6/6/2020 var aBall; function setup() { aBall1 = new BallInDiv(300, 150, "red", 10); aBall2 = new BallInDiv(200, 200, "green", 10); aBall3 = new BallInDiv(400, 150, "blue", 10); } // setup function draw() { aBall1.draw(); aBall2.draw(); aBall3.draw(); } // draw function ball(x, y, r, cnvs) { // https://www.youtube.com/watch?v=YkNO-wu0190 // by Sonny Sandberg with the addition of adding cnvs as an parameter. this.x = x; this.y = y; this.r = r this.d = 2*r; this.xVelocity = -4; this.yVelocity = 3; this.show = function() { cnvs.ellipse(this.x, this.y, this.d); } this.move = function() { this.x += this.xVelocity; this.y += this.yVelocity; this.bounce(); } this.bounce = function() { if (this.x - this.r < 0 || this.x + this.r > cnvs.width) { this.xVelocity *= -1; } if (this.y - this.r < 0 || this.y + this.r > cnvs.height) { this.yVelocity *= -1; } } } class BallInDiv { constructor (canvasWidth, canvasHeight, bgColor, ballSize) { this.bgColor = bgColor; this.div = createDiv(); this.div.parent("p5"); this.cnvs = createCanvasClass(canvasWidth, canvasHeight); this.cnvs.parent(this.div); this.ball = new ball(ballSize + random(canvasWidth - 2 * ballSize), ballSize + random(canvasHeight - 2 * ballSize), ballSize, this.cnvs); } draw = function() { this.cnvs.background(this.bgColor); this.ball.show(); this.ball.move(); } }