91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
const CollectableValues = {
|
|
Small: 1,
|
|
Medium: 5,
|
|
Big: 10,
|
|
};
|
|
|
|
class Collectable extends AnimatedSprite {
|
|
|
|
constructor(x, y) {
|
|
super(Collectable.texture, 14);
|
|
this.size = 0.1;
|
|
this.width = this.height = this.size;
|
|
this.x = x;
|
|
this.y = y;
|
|
this.collected = false;
|
|
this.maxTimer = 30;
|
|
|
|
let rand = Math.random();
|
|
|
|
if (rand < 0.6) {
|
|
this.value = CollectableValues.Small;
|
|
} else if (rand < 0.9) {
|
|
this.value = CollectableValues.Medium;
|
|
} else {
|
|
this.value = CollectableValues.Big;
|
|
}
|
|
}
|
|
|
|
textureOffset() {
|
|
switch (this.value) {
|
|
case CollectableValues.Small:
|
|
return 0;
|
|
case CollectableValues.Medium:
|
|
return 64;
|
|
case CollectableValues.Big:
|
|
return 128;
|
|
}
|
|
}
|
|
|
|
update(time = 0.02) {
|
|
if (!this.collected) {
|
|
super.update(time);
|
|
} else {
|
|
this.textTimer += time * 50;
|
|
}
|
|
}
|
|
|
|
collect() {
|
|
this.collected = true;
|
|
this.textTimer = 0;
|
|
return this.value;
|
|
}
|
|
|
|
drawOn(canvas, context) {
|
|
if (!this.collected) {
|
|
context.drawImage(
|
|
this.spriteSheet,
|
|
this.textureOffset(), 64 * this.currentFrame, 64, 64,
|
|
(this.x - this.width / 2) * canvas.width,
|
|
(1 - this.y) * canvas.height - this.height * canvas.width / 2,
|
|
this.width * canvas.width,
|
|
this.height * canvas.width,
|
|
);
|
|
} else if (this.textTimer < this.maxTimer) {
|
|
this.drawTextOn(canvas, context);
|
|
}
|
|
}
|
|
|
|
alphaFromTimer() {
|
|
return 1 - this.textTimer / this.maxTimer;
|
|
}
|
|
|
|
drawTextOn(canvas, context) {
|
|
context.font = "15px Dimbo";
|
|
context.fillStyle = 'rgba(0, 200, 0, ' + this.alphaFromTimer() + ')';
|
|
|
|
let text = "+" + this.value;
|
|
let width = context.measureText(text).width;
|
|
|
|
context.fillText(text,
|
|
this.x * canvas.width - width / 2,
|
|
(1 - this.y) * canvas.height - this.textTimer
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Collectable.texture = new Image();
|
|
Collectable.texture.src = "img/collectable.png";
|