JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js"></script>
<body>
</body>
CSS
canvas {
position: relative;
margin: 0 auto;
}
JavaScript
var game = new Phaser.Game(window.innerWidth, 300, Phaser.AUTO, 'phaser-example', { create: create });
var healthBar;
var attackBtn;
var hp_status_text;
var maxHealth = 100;
var health = 100;
var config = {
hpBar: null,
atckBtn: null
}
function create() {
addHealthBar({
pos: {
x: game.world.centerX,
y: 20
},
size: {
w: game.world.width - 40,
h: 20,
_1p: 0 /// will be calculated later
},
fill_c: 0x00cc00,
border_c: 0x80ff80,
alpha: 0.7
});
addAttackButton({
pos: {
x: game.world.centerX,
y: 65
},
size: {
w: 90,
h: 35,
},
fill_c: 0xff1a1a,
border_c: 0xff8080,
alpha: 0.7
});
}
/////// [ Health Bar ] ///////////////////
function takeDamage( damage ){
if( Math.floor(health) > 0 ){
health -= damage;
}else{
console.log("dead");
}
let hp_p = ( health / maxHealth ) * 100;
updateHealthBar( hp_p );
}
function addHealthBar( cfg ){
config.hpBar = cfg;
config.hpBar.pos.x -= ( config.hpBar.size.w / 2 ); /// center on X axis ////
config.hpBar.size._1p = config.hpBar.size.w * 0.01; ///// 1% of width ///
healthBar = game.add.graphics( config.hpBar.pos.x, config.hpBar.pos.y );
hp_status_text = game.make.text( 0 , 0, "", { font: "bold 22px Arial", fill: "#FFF", boundsAlignH: "center", boundsAlignV: "middle"} );
hp_status_text.setTextBounds(0, 2, config.hpBar.size.w, config.hpBar.size.h);
healthBar.addChild(hp_status_text);
updateHealthBar( 100 ); /// 100 % life ////
}
function updateHealthBar( hp_p ){ //// health percentage
healthBar.clear();
hp_status_text.setText( Math.floor(hp_p)+"%" );
healthBar.lineStyle( 2, config.hpBar.border_c, config.hpBar.alpha );
healthBar.beginFill( config.hpBar.fill_c, config.hpBar.alpha );
healthBar.drawRect( 0, 0, hp_p * config.hpBar.size._1p , config.hpBar.size.h );
healthBar.endFill();
}
/////// [ Health Bar ] ///////////////////
/////// [ Attack Button ] ///////////////////
function addAttackButton( cfg ){
config.atckBtn =...