Talking about Game development, HTML5, Javascript and Phaser.
When my games need a time or energy bar – shame on me – I usually build it using a plain rectangle sprite and adjusting its size according to the data I need to display.
This time I wanted to create something better, a more complex time meter with is container and the energy bar a little more good looking than a simple rectangle.
At the same time, I did not want to create a lot of layered images, so I ended up with only two PNGs, one for the energy bar:
and one for the container:
Now the point is how to handle the energy bar without slicing it in smaller images or creating layered PNGs.
I used a copy of the energy bar itself, and simply moved it to the left.
Look at the example:
Easy and simple, just using a mask. Try to do it without masks and it will be a nightmare.
Look at the source code:
let game;
let gameOptions = {
initialTime: 60
}
window.onload = function() {
let gameConfig = {
type: Phaser.AUTO,
backgroundColor:0x1a213e,
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: "thegame",
width: 750,
height: 200
},
scene: playGame,
}
game = new Phaser.Game(gameConfig);
window.focus();
}
class playGame extends Phaser.Scene{
constructor(){
super("PlayGame");
}
preload(){
this.load.image("energycontainer", "energycontainer.png");
this.load.image("energybar", "energybar.png");
}
create(){
this.timeLeft = gameOptions.initialTime;
// the energy container. A simple sprite
let energyContainer = this.add.sprite(game.config.width / 2, game.config.height / 2, "energycontainer");
// the energy bar. Another simple sprite
let energyBar = this.add.sprite(energyContainer.x + 46, energyContainer.y, "energybar");
// a copy of the energy bar to be used as a mask. Another simple sprite but...
this.energyMask = this.add.sprite(energyBar.x, energyBar.y, "energybar");
// ...it's not visible...
this.energyMask.visible = false;
// and we assign it as energyBar's mask.
energyBar.mask = new Phaser.Display.Masks.BitmapMask(this, this.energyMask);
// a boring timer.
this.gameTimer = this.time.addEvent({
delay: 1000,
callback: function(){
this.timeLeft --;
// dividing enery bar width by the number of seconds gives us the amount
// of pixels we need to move the energy bar each second
let stepWidth = this.energyMask.displayWidth / gameOptions.initialTime;
// moving the mask
this.energyMask.x -= stepWidth;
if(this.timeLeft == 0){
this.scene.start("PlayGame")
}
},
callbackScope: this,
loop: true
});
}
};
Now you have no excuses to use those flat, ugly, cheap rectangles. Download the source code.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.