In this recipe, we'll create a Health Bar class which is used to update and render the hero's health display.
Follow these steps to create a health bar class:
Define the
HealthBar
constructor:/* * HealthBar class should have no knowledge * of the Actor or Level classes to * keep it decoupled */ function HealthBar(config){ this.controller = config.controller; this.maxHealth = config.maxHealth; this.x = config.x; this.y = config.y; this.maxWidth = config.maxWidth; this.height = config.height; this.health = this.maxHealth; }
Define the
setHealth()
method which sets the health value:HealthBar.prototype.setHealth = function(health){ this.health = health; };
Define the
draw()
method which draws the health bar:HealthBar.prototype.draw = function(){ var context = this.controller.view.context; context.beginPath(); context.rect(this.x, this.y, this.maxWidth, this.height); context.fillStyle = "black"; context...