{"id":195,"date":"2011-12-02T20:24:46","date_gmt":"2011-12-03T01:24:46","guid":{"rendered":"http:\/\/blog.cubicleninja.com\/?p=195"},"modified":"2026-06-07T10:28:42","modified_gmt":"2026-06-07T15:28:42","slug":"javascript-and-html5-simple-game-creation-part-6","status":"publish","type":"post","link":"https:\/\/blog.cubicleninja.com\/?p=195","title":{"rendered":"JavaScript and HTML5 \u2013 Simple Game Creation Tutorial (part 6)"},"content":{"rendered":"<p>Finally we get to part 6 of the game creation tutorial \/ learning endeavor.  Reality conspired against me to cause this post to be delayed, but I got here all the same.   Today we&#8217;re going to dig into creating goodness, gracious great balls of fire for our hero to throw around in a devil-may-care fashion.  The image we&#8217;ll be using for our fireball sprite is one I found somewhere ages ago (honestly, no clue when or where I got it) and slightly modified to meet the needs of this game.  It follows the same pattern as our other animate sprite (for the hero \/ villains) and is just a sequence of &#8220;keyframes&#8221; for the sprite with a transparent background.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/html5.cubicleninja.com\/images\/fireballs.png\" alt=\"fireballs!\" \/><\/p>\n<p>Several of the pieces for the fireball object will be directly duplicated from our hero object (because, really, fireballs and people share, like, 95% of the same DNA sequences).  We will have one main new concept that will be introduced:  destroying \/ recreating an object.   We want to ensure that when our fireball hits a wall, enemy or the edge of the world it is destroyed to free up the memory allocated for it (and to make sure invisible fireballs don&#8217;t keep roaming around all higgledy-piggledy).  <\/p>\n<p>As I mentioned, the fireball object is going to be almost identical to the hero object.  We&#8217;ll adjust the width and height to be 16 instead of 32, change the speed a little and (the biggest change) give it a destroyed property that will be set to true when it goes off the screen:<\/p>\n<pre class=\"lang:js decode:true\">\nfunction fireball()\n{\n\n    \/\/ The width and height of the sprites for our fireball\n    this.width = 16;\n    this.height = 16;\n    \/\/ When our fireball is first created is in null land\n    \/\/ we assign a location based upon where the hero is\n    this.x = null;\n    this.y = null;\n    \/\/ An array to hold the information about which keyboard keys are pressed\n    this.keys = new Array();\n    \/\/ When was the last time we drew the fireball to the screen\n    this.lastRender = Date.now();\n    \/\/ What delay do we want to use between switching sprites (in milliseconds)\n    this.animSpeed = 100;\n    \/\/ What image are we using for the hero\n    this.image = new Image();\n    \/\/ Which sprite in the image are we currently rendering\n    this.whichSprite = 0;\n    \/\/ How many pixels do we want to move the fireball each loop\n    this.moveSpeed = 7;\n    \/\/ Do we have a collision event?\n    this.collision = false;\n    \/\/ When was the last time we had a direction change?\n    this.lastKeyChange = Date.now();\n    \/\/ Do we need to destroy the fireball?\n    this.destroyed = false;\n\n    this.render = function()\n    {\n        \/\/ drawImage takes for parameters:\n        \/\/      the image to draw\n        \/\/      the x and y coordinates to use from the source image\n        \/\/      the width and height to use from the source image\n        \/\/      the x and y coordinates to draw it to on the canvas\n        \/\/      the width and height to draw it into on the canvas\n        context.drawImage(this.image, this.whichSprite, 0, this.width, this.height, this.x, this.y, this.width, this.height);\n    };\n\n    this.checkCollision = function(obj)\n    {\n        \/\/ check to see if our x coordinate is inside the object and\n        \/\/ our y coordinate is also inside the object\n        \/\/ Adjust these to give 1 full pixel lenience due to canvas allowing \n        \/\/ partial pixel rendering\n        if ((this.x < (obj.x + obj.width - 1) &#038;&#038; Math.floor(this.x + this.width - 1) > obj.x)\n            && (this.y < (obj.y + obj.height - 1) &#038;&#038; Math.floor(this.y + this.height - 1) > obj.y))\n        {\n            return true;\n        }\n    };\n\n    this.update = function(elapsed)\n    {\n        \/\/ store out the current x and y coordinates\n        var prevX = this.x;\n        var prevY = this.y;\n        \/\/ reset the collision property\n        this.collision = false;\n\n        var now = Date.now();\n        \/\/ How long has it been since we last updated the sprite\n        var delta = now - this.lastRender;\n\n        \/\/ perform a switch statement on the last key pushed into the array\n        \/\/ this allows us to always move the direction of the most recently pressed\n        \/\/ key\n        switch (this.keys[this.keys.length - 1])\n        {\n            case 37:\n                \/\/ move the fireball left on the screen\n                this.x -= this.moveSpeed * elapsed;\n                \/\/ Check if the animation timer has elapsed\n                if (delta > this.animSpeed)\n                {\n                    this.whichSprite = this.whichSprite == 0 ? 16 : this.whichSprite == 16 ? 32 : this.whichSprite == 32 ? 48 : 0;\n                    this.lastRender = now;\n                }\n                break;\n            case 38:\n                \/\/ move the fireball up on the screen\n                this.y -= this.moveSpeed * elapsed;\n                \/\/ Check if the animation timer has elapsed\n                if (delta > this.animSpeed)\n                {\n                    this.whichSprite = this.whichSprite == 0 ? 16 : this.whichSprite == 16 ? 32 : this.whichSprite == 32 ? 48 : 0;\n                    this.lastRender = now;\n                }\n                break;\n            case 39:\n                \/\/ move the fireball right on the screen\n                this.x += this.moveSpeed * elapsed;\n                \/\/ Check if the animation timer has elapsed\n                if (delta > this.animSpeed)\n                {\n                    this.whichSprite = this.whichSprite == 0 ? 16 : this.whichSprite == 16 ? 32 : this.whichSprite == 32 ? 48 : 0;\n                    this.lastRender = now;\n                }\n                break;\n            case 40:\n                \/\/ move the fireball down on the screen\n                this.y += this.moveSpeed * elapsed;\n                \/\/ Check if the animation timer has elapsed\n                if (delta > this.animSpeed)\n                {\n                    this.whichSprite = this.whichSprite == 0 ? 16 : this.whichSprite == 16 ? 32 : this.whichSprite == 32 ? 48 : 0;\n                    this.lastRender = now;\n                }\n                break;\n        }\n        \n        \/\/ Logic to see if we're going off the screen\n        \/\/ If we do we are destroyed\n        if (this.x < -this.width)\n        {\n            this.destroyed = true;\n        }\n        if (this.x >= renderW)\n        {\n            this.destroyed = true;\n        }\n        if (this.y < -this.height)\n        {\n            this.destroyed = true;\n        }\n        if (this.y >= renderH)\n        {\n            this.destroyed = true;\n        }\n    };\n}\n<\/pre>\n<p>Much like we did for the enemies and the rocks, we&#8217;re going to need a base fireball object that we will load the image into in order to speed things along as we are playing.  At the top, underneath <\/p>\n<pre class=\"lang:js decode:true\"> we'll add in:\n\n<pre class=\"lang:js decode:true\">\n\/\/ variable to hold our base fireball image\nvar baseFireball;\n<\/pre>\n<p>And we need a new function to initialize the base fireball object (it's actually only two lines of code, but we're doing it for consistency since we did it for all the other objects):<\/p>\n<pre class=\"lang:js decode:true\">\nfunction initFireball()\n{\n    baseFireball = new Image();\n    baseFireball.src = \"images\/fireballs.png\";\n}\n<\/pre>\n<p>Now just add a call to <\/p>\n<pre class=\"lang:js decode:true\">.\n\nOnce we know what a fireball is and have the base all set, we're going to make it up so that our hero is only allowed to have one active fireball in play at a given time.   We'll start off by just adding a new property to our hero object called \"activeFireball\" and a boolean \"shooting\" variable.  Inside our <pre class=\"lang:js decode:true\"> add:\n\n<pre class=\"lang:js decode:true\">\n    \/\/ Do we have an active fireball in play?\n    this.activeFireball = null;\n    \/\/ Rather than using the keys array for fireballs, we'll just have a boolean\n    this.shooting = false;\n<\/pre>\n<p>Now we'll make a slight adjustment to our key capture logic to trap a press of the spacebar (we'll add logic into our hero later to check for this in order to Hadouken!).  At the top of the keydown and keyup handlers we'll add a check to see if the spacebar was pressed.  This is the code for the keydown event, the keyup event is the same code except we set the value to false:<\/p>\n<pre class=\"lang:js decode:true\">\n    \/\/ check if the spacebar is being pressed\n    if (event.keyCode == 32)\n        hero.shooting = true;\n<\/pre>\n<p>Now we're all set capturing the spacebar (why the spacebar, you may ask?  Because that's what it always seems to be in games, just accept it).  The next piece is to adjust our hero update method to check for the spacebar being pressed and, if it is, start up a fireball object.   This code will go inside the update method, just above the switch statement for the hero movement:<\/p>\n<pre class=\"lang:js decode:true\">\n        \/\/ check to see if the spacebar is being pressed        \n        if (this.shooting)\n        {\n            \/\/ check to make sure we don't currently have a fireball in play\n            if (this.activeFireball == null)\n            {\n                \/\/ create a new fireball inside our hero object\n                this.activeFireball = new fireball();\n                \/\/ set the image to use the base fireball we loaded\n                this.activeFireball.image = baseFireball;\n\n                \/\/ check which way our hero is facing, we use this to determine\n                \/\/ where we position the fireball, which direction the fireball\n                \/\/ has to move and which set of 4 sprites we use\n                if (this.whichSprite < this.width * 2)\n                {\n                    this.activeFireball.keys[0] = 40;\n                    this.activeFireball.x = this.x + (this.width \/ 4);\n                    this.activeFireball.y = this.y + this.height;\n                }\n                else if (this.whichSprite < this.width * 4)\n                {\n                    this.activeFireball.keys[0] = 37;\n                    this.activeFireball.x = this.x;\n                    this.activeFireball.y = this.y + (this.height \/ 4);\n                }\n                else if (this.whichSprite < this.width * 6)\n                {\n                    this.activeFireball.keys[0] = 39;\n                    this.activeFireball.x = this.x + this.width;\n                    this.activeFireball.y = this.y + (this.height \/ 4);\n                }\n                else\n                {\n                    this.activeFireball.keys[0] = 38;\n                    this.activeFireball.x = this.x + (this.width \/ 4);\n                    this.activeFireball.y = this.y;\n                }\n                \n                this.activeFireball.render();\n            }\n        }\n<\/pre>\n<p>The steps we are having the code perform are:  check if the spacebar was just pressed -- if so, remove the spacebar from the keys array (we do this because we want the movement switch to go based upon the last arrow key that was pressed) and check if the hero currently has an active fireball -- if not, create a new fireball object and position it based upon which way the hero is facing then draw it to the screen.<\/p>\n<p>The last change we have to make to get our fireball moving on the screen (but not finished since it will just go on forever at this point) is to add the logic into our <\/p>\n<pre class=\"lang:js decode:true\">:\n\n<pre class=\"lang:js decode:true\">   \n    \/\/ if the hero has a fireball, render it\n    if (hero.activeFireball != null)\n    {\n        \/\/ Update the fireball based upon how long it took for the game loop\n        hero.activeFireball.update(elapsed \/ timerRatio);\n\n        \/\/ if our fireball was destroyed in the last update, remove it\n        \/\/ otherwise draw it to the screen\n        if (hero.activeFireball.destroyed)\n            hero.activeFireball = null;\n        else\n            hero.activeFireball.render();\n    }\n<\/pre>\n<p>When you run the code at this point you should be able to press the spacebar and have it shoot off a fireball.  The fireball will be destroyed when it goes off the screen allowing you to shoot another.   At the moment, the fireballs will pass right through the rocks and enemies and that just will NOT do!   We'll fix that glaring oversight by adding calls to the collisionCheck inside the fireball update method.   For the rocks we'll take the code we already have in place within the hero object that loops through and checks for collisions.   We need to make a small tweak to it so that it tells the fireball to bugger off when it has a collision<\/p>\n<pre class=\"lang:js decode:true\">\n        \/\/ loop through all of the rocks in the array\n        \/\/ we use an for-in loop to go through the rocks in case\n        \/\/ we later add some logic that can destroy static objects\n        \/\/ a regular for loop could break with null values if that happens\n        for (iter in rocks)\n        {\n            \/\/ check to see if we have a collision event with the\n            \/\/ current rock\n            if (this.checkCollision(rocks[iter]))\n            {\n                \/\/ we hit a rock, we need to destroy the fireball\n                this.destroyed = true;\n                break;\n            }\n        }\n<\/pre>\n<p>Great, now we can toss fireballs around the map and have them be destroyed when they go off screen or hit a rock.  Of course, the REAL fun comes from being able to shoot the enemies.  To accommodate the need for wanton destruction and the killing of cute, onscreen pixels, we need to add a new property into our heroObject (remember the heroObject is used for both the hero and the enemies).  Right below the <\/p>\n<pre class=\"lang:js decode:true\"> line we added earlier we'll add in \n\n<pre class=\"lang:js decode:true\">\n    \/\/ Did we get hit by a fireball and need to be destroyed?\n    this.destroyed = false;\n<\/pre>\n<p>Next step is adjusting the fireball update method to also iterate through all of the enemies to check for a collision.  We'll add this code after the loop through all of the rocks:<\/p>\n<pre class=\"lang:js decode:true\">\n        \/\/ loop through all of the enemies in the array\n        \/\/ we use an for-in loop to go through the enemies in case\n        \/\/ we later add some logic that can destroy an enemy objects\n        \/\/ a regular for loop could break with null values if that happens\n        for (iter in enemies)\n        {\n            \/\/ check to see if we have a collision event with the\n            \/\/ current enemy\n            if (this.checkCollision(enemies[iter]))\n            {\n                \/\/ we hit an enemy, we need to destroy the fireball\n                \/\/ and the enemy\n                this.destroyed = true;\n                enemies[iter].destroyed = true;\n                break;\n            }\n        }\n<\/pre>\n<p>That tells it to destroy both the enemy AND the fireball when we have a collision between the two.   We have one final piece of the puzzle and that is to update the gameLoop to have it remove the enemy from the game if it is destroyed.  We'll replace the foreach loop through the enemies within the gameLoop with the following:<\/p>\n<pre class=\"lang:js decode:true\">\n    \/\/ do a foreach type loop through the enemies\n    for (curEnemy in enemies)\n    {\n        if (enemies[curEnemy].destroyed)\n        {\n            enemies.splice(curEnemy, 1);\n        }\n        else\n        {\n            \/\/ Update the enemy based upon how long it took for the game loop\n            enemies[curEnemy].update(elapsed \/ timerRatio);\n\n            \/\/ check if the enemy collided with a rock, if it did turn it a random direction\n            if (enemies[curEnemy].collision)\n            {\n                enemies[curEnemy].keys[0] = Math.floor(Math.random() * 4) + 37;\n                enemies[curEnemy].lastKeyChange = Date.now();\n            }\n\n            \/\/ if the enemy has gone a while without changing directions, turn it a random direction\n            if (now - enemies[curEnemy].lastKeyChange > ((Math.random() * 3000) + 5000))\n            {\n                enemies[curEnemy].keys[0] = Math.floor(Math.random() * 4) + 37;\n                enemies[curEnemy].lastKeyChange = Date.now();\n            }\n\n            \/\/ draw the enemy to the screen again\n            enemies[curEnemy].render();\n        }\n    }\n<\/pre>\n<p>And that does it.  You can know wield flaming balls of death (well flaming ball of death since you can only have one at a time) that will destroy enemies and disappear off the screen.  This post covered a fairly large amount of changes, so if anything doesn't make sense feel free to let me know.   Here's a screenshot of a fireball in action.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/html5.cubicleninja.com\/images\/SimpleGame_6.png\" alt=\"Simple Game 6 - Sample Image\" \/><\/p>\n<p>And, as always, the link to the <a href=\"https:\/\/html5.cubicleninja.com\/SimpleGame_6.htm\">demo for this code<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Finally we get to part 6 of the game creation tutorial \/ learning endeavor. Reality conspired against me to cause this post to be delayed, but I got here all the same. Today we&#8217;re going to dig into creating goodness, gracious great balls of fire for our hero to throw around in a devil-may-care fashion. &hellip; <a href=\"https:\/\/blog.cubicleninja.com\/?p=195\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;JavaScript and HTML5 \u2013 Simple Game Creation Tutorial (part 6)&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5,7],"tags":[17,25,29,31,32,39],"class_list":["post-195","post","type-post","status-publish","format-standard","hentry","category-html5","category-javascript","tag-canvas","tag-game","tag-html5","tag-javascript","tag-jquery","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/195","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=195"}],"version-history":[{"count":2,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/195\/revisions"}],"predecessor-version":[{"id":21800,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=\/wp\/v2\/posts\/195\/revisions\/21800"}],"wp:attachment":[{"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=195"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=195"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.cubicleninja.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=195"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}