/* * Copyright (c) 2020. Antonio Martinez Casadesus and Pascal Syma. * All rights reserved. */ export default class Entity extends Phaser.GameObjects.Sprite { constructor(scene, x, y, key) { super(scene, x, y, key); this.setData('hp', 1); this.setData('dmg', 0); this.scene = scene; this.scene.add.existing(this); this.scene.physics.world.enableBody(this, 0); this.hitAnimation = null; this.dieAnimation = null; } hit(dmg) { if (dmg === 0) return; if (this.hitCooldown) return; this.hitCooldown = true; const newHp = this.getData('hp') - dmg; this.setData('hp', newHp < 0 ? 0 : newHp); // play hit animation const shouldDie = this.getData('hp') <= 0; if (shouldDie) { this.body.velocity.x = 0; this.setData('active', false); this.die(); } else { setTimeout(() => this.hitCooldown = false, 1000); } } die() { if (this.dieAnimation !== null && this.active) { this.setData('active', false); this.play(this.dieAnimation) .once('animationcomplete', () => this.destroy()); } else this.destroy(); } update(...args) { super.update(...args); } }