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
<html>
<head>
<style>
canvas {
position: relative;
margin: 0 auto;
}
</style>
</head>
<body>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/phaser/2.6.2/phaser.min.js"></script>
<script>
var game = new Phaser.Game(window.innerWidth, 300, Phaser.AUTO, 'phaser-example', { create: create, preload: preload });
var healthBar;
var cropRect;
var attackBtn;
var maxHealth = 100;
var health = 100;
var config = {
hpBar: null,
atckBtn: null
}
function preload() {
game.load.image('hpbar', 'hpbar.png');
}
function create() {
addHealthBar({
pos: {
x: game.world.centerX,
y: 20
},
_1p: 0 //// willbe calculated dinamically ///
});
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;
healthBar = game.add.sprite( config.hpBar.pos.x, config.hpBar.pos.y, "hpbar" );
config.hpBar._1p = healthBar.width * 0.01;
healthBar.position.x -= healthBar.width /2; /// center on X axis ///
healthBar.anchor.setTo(0, 0.5);
cropRect = new Phaser.Rectangle(0, 0, healthBar.width, healthBar.height);
healthBar.crop(cropRect);
updateHealthBar( 100 ); /// 100 % life ////
}
function updateHealthBar( hp_p ){ //// health percentage
cropRect.width = hp_p * config.hpBar._1p ;
healthBar.updateCrop();
}
/////// [ Health Bar ] ///////////////////
/////// [ Attack Button ] ///////////////////
function addAttackButton( cfg ){
config.atckBtn = cfg;
config.atckBtn.pos.x -= ( config.atckBtn.size.w / 2 ); /// center on X axis ////
attackBtn = game.add.graphics( config.atckBtn.pos.x, config.atckBtn.pos.y );
let t = game.make.text( 0 , 0,...