8.5 创建Health Bar类
优质
小牛编辑
127浏览
2023-12-01
本节,我们将创建HealthBar类,用来更新并渲染英雄的生命值:
操作步骤
按照以下步骤,创建HealthBar类:
1. 定义构HealthBar类的造函数:
/* HealthBar类应该对Actor或Level类一无所知,
* 以便它们之间是解耦的
*/
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;
}
2. 定义setHealth ()方法,该方法设置生命值:
HealthBar.prototype.setHealth = function(health){
this.health = health;
};
3. 定义draw()方法,该方法绘制生命值条:
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.fill();
context.closePath();
context.beginPath();
var width = this.maxWidth * this.health / this.maxHealth;
context.rect(this.x, this.y, width, this.height);
context.fillStyle = "red";
context.fill();
context.closePath();
};
工作原理
HealthBar对象有一个简单的构造函数,来初始化生命值条的位置和尺寸。并包含setHealth() 和 draw()两个方法,setHealth()方法设置HealthBar对象的health属性,draw()方法调用画布上下文对象的rect()方法绘制生命值条。