56 lines
1.4 KiB
JavaScript
56 lines
1.4 KiB
JavaScript
class Bar {
|
|
constructor(ctx, key) {
|
|
this.ctx = ctx;
|
|
this.key = key;
|
|
|
|
this.w = 100;
|
|
this.h = 20;
|
|
this.speed = 10; // Target Speed
|
|
this._speed = 0; // Current Speed and direction
|
|
|
|
this.xLimit = (ctx.canvas.width - this.w);
|
|
this.reset();
|
|
}
|
|
reset() {
|
|
this.x = (this.ctx.canvas.width - this.w) / 2;
|
|
this._y = (this.ctx.canvas.height - this.h * 2);
|
|
|
|
this.y = this.ctx.canvas.height + 10;
|
|
}
|
|
update() {
|
|
this.move();
|
|
this.draw();
|
|
}
|
|
stop() {
|
|
this._speed = 0;
|
|
}
|
|
left() {
|
|
if (this._speed >= 0) this._speed = -this.speed;
|
|
this.x += this._speed;
|
|
if (this.x < 0) this.x = 0;
|
|
this._speed -= 0.5;
|
|
}
|
|
right() {
|
|
if (this._speed <= 0) this._speed = this.speed;
|
|
this.x += this._speed;
|
|
if (this.x > this.xLimit) this.x = this.xLimit;
|
|
this._speed += 0.5;
|
|
}
|
|
move() {
|
|
if (this.key.isDown('ArrowLeft')) this.left();
|
|
else
|
|
if (this.key.isDown('ArrowRight')) this.right();
|
|
else
|
|
this.stop();
|
|
}
|
|
|
|
|
|
draw() {
|
|
if (this.y != this._y) this.y--;
|
|
if (this.y < this.ctx.canvas.height) {
|
|
this.ctx.fillStyle = 'black';
|
|
this.ctx.fillRect(this.x, this.y, this.w, this.h);
|
|
}
|
|
}
|
|
}
|