breakout/Ball.js

98 lines
2.7 KiB
JavaScript

class Ball {
constructor(ctx, bar) {
this.ctx = ctx;
this.bar = bar;
this.size = 15;
this.moving = false;
this.x = this.bar.x + (this.bar.w) / 2;
this.y = this.bar.y - this.size -1;
this.speed = 5;
// this.angle = 90;
this.bounce(220,340);
this.color = 'red';
this.limits = {
l: this.size,
t: this.size,
r: this.ctx.canvas.width - this.size,
b: this.ctx.canvas.height
}
}
start() {
this.moving = true;
}
update() {
if (this.move()) {
this.draw();
return true;
}
return false;
}
draw() {
this.ctx.beginPath();
this.ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI, false);
this.ctx.fillStyle = this.color;
this.ctx.fill();
this.ctx.lineWidth = 1;
this.ctx.strokeStyle = '#003300';
this.ctx.stroke();
}
move() {
if (this.moving) {
this.x += this.speed * Math.cos(this.angle);
this.y += this.speed * Math.sin(this.angle);
// Escaped from the pad
if (this.y > this.limits.b) {
this.moving = false;
return false;
}
if (this.y > this.bar.y ) return true; // Ball is lost, don't check anything else
if ( (this.y + this.size) > this.bar.y && this.x > this.bar.x && this.x < (this.bar.x + this.bar.w) ) {
// Down (Bar)
this.bounce(220,340);
} else {
if ( this.x < this.limits.l ) {
// Left wall
if (this.angle<this.g2r(180)) this.bounce(20,70); // It was going DOWN
else this.bounce(290,340); // It was going UP
} else
if ( this.x > this.limits.r ) {
// Right wall
if (this.angle<this.g2r(180)) this.bounce(110,160); // It was going DOWN
else this.bounce(200,250); // It was going UP
} else
if ( this.y < this.limits.t ) {
// Top Wall
this.bounce(20,140);
}
}
} else {
this.x = this.bar.x + (this.bar.w) / 2;
this.y = this.bar.y - this.size -1;
}
return true;
}
bounce(min,max) {
this.angle = this.g2r( Math.floor(Math.random() * (max-min)) + min );
}
g2r(deg) {
console.log((360+deg)%360);
return ( ((360+deg)%360) * Math.PI) / 180.0;
}
r2g(rad) {
return rad*180 / Math.PI;
}
}