Javascript Canvas Game Slay Monster
Slaying monsters in our javascript arena.
var slayMonster = function() {
if(isTouching(hero, monster)) {
monster.x = 100;
monster.y = 100;
}
};
var isTouching = function(a, b) {
var ret = false;
if((a.x <= (b.x + b.width)) && (b.x <= (a.x + b.width)) && (a.y <= (b.y + b.height)) && (b.y <= (a.y + b.height))) {
ret = true;
}
return ret;
};
Slay monster function simply checks if the hero and monster are touching and then respawns the monster at location 100, 100.
The slayMonster function should be called in the main function.
slayMonster();
It’s more fun if we had some stats on how many monsters we have slain. Add a variable to the hero array to keep track of how many monsters have been slain.
hero.monstersSlain = 0;
Now in the slayMonsters if isTouching block add an incrementer.
++hero.monstersSlain;
We need to show this on the screen. Add an HTML element to store the stat in. We’ll also need jQuery, a helpful javascript library.
<div id="monsters_slain_header">
<span>Monsters Slain: </span><span id="monsters_slain">0</span>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
To push the monsters slain count to the html element, add this to your render function.
$('#monsters_slain').html(hero.monstersSlain);
Let’s add some styling to our stat bar.
#monsters_slain_header { color: white; font-weight: bold; font-size: 18px; margin: 10px 15px; }
You can download this example.