escalator-web/src/collectable.js

91 lines
2.2 KiB
JavaScript
Raw Normal View History

2018-08-27 14:32:01 +02:00
const CollectableValues = {
Small: 1,
Medium: 5,
Big: 10,
};
2018-08-27 10:47:48 +02:00
class Collectable extends AnimatedSprite {
2018-08-24 11:49:25 +02:00
constructor(x, y) {
2018-08-27 10:47:48 +02:00
super(Collectable.texture, 14);
2018-08-24 11:49:25 +02:00
this.size = 0.1;
2018-08-27 10:47:48 +02:00
this.width = this.height = this.size;
2018-08-24 11:49:25 +02:00
this.x = x;
this.y = y;
this.collected = false;
2018-08-27 10:47:48 +02:00
this.maxTimer = 30;
2018-08-27 14:32:01 +02:00
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;
}
2018-08-26 21:53:16 +02:00
}
update(time = 0.02) {
2018-08-27 10:47:48 +02:00
if (!this.collected) {
super.update(time);
} else {
this.textTimer += time * 50;
}
}
2018-08-26 21:53:16 +02:00
2018-08-27 10:47:48 +02:00
collect() {
this.collected = true;
this.textTimer = 0;
2018-08-27 14:32:01 +02:00
return this.value;
2018-08-27 10:47:48 +02:00
}
drawOn(canvas, context) {
if (!this.collected) {
2018-08-27 14:32:01 +02:00
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,
);
2018-08-27 10:47:48 +02:00
} else if (this.textTimer < this.maxTimer) {
this.drawTextOn(canvas, context);
2018-08-26 21:53:16 +02:00
}
2018-08-24 11:49:25 +02:00
}
2018-08-27 10:47:48 +02:00
alphaFromTimer() {
return 1 - this.textTimer / this.maxTimer;
}
drawTextOn(canvas, context) {
context.font = "15px Dimbo";
context.fillStyle = 'rgba(0, 200, 0, ' + this.alphaFromTimer() + ')';
2018-08-27 14:32:01 +02:00
let text = "+" + this.value;
let width = context.measureText(text).width;
2018-08-27 10:47:48 +02:00
2018-08-27 14:32:01 +02:00
context.fillText(text,
2018-08-27 10:47:48 +02:00
this.x * canvas.width - width / 2,
(1 - this.y) * canvas.height - this.textTimer
);
}
2018-08-24 11:49:25 +02:00
}
Collectable.texture = new Image();
Collectable.texture.src = "img/collectable.png";