Let’s build an HTML5 game! (Beginner Tutorial, Part 1)

Let’s build an HTML5 game! (Beginner Tutorial, Part 1)

Building an HTML5 game.

So, you want build an HTML5 game? Welcome to the club!

HTML5 is the newest platform for building games for general audiences and many developers are looking to get in on the action. This tutorial will get you started whether you are targeting desktop browsers, mobile browsers, native applications via Apache Cordova (Phonegap) or Windows Phone or all of the above.

We will attempt to construct a prototype of a some-what playable game, exploring some concepts along the way. The first concept we will tackle our rendering approach.

Canvas versus WebGL versus DOM

I typically eliminate WebGL from consideration due to its still low adoption rate on mobile. If you are only targeting desktop browsers, WebGL is probably a better option than canvas. So, if you are considering targeting mobile browsers with your HTML5 game, you will need to choose between canvas 2D and using the DOM (document object model).

If you choose canvas, there are lots of javascript game engines that use canvas to power their engines. However, I will try and make a case here for using the DOM. Actually, what I use is mixture of DOM and canvas to be honest. On my game Space Cute: Beginnings I use DOM for animations and interactions and layer a canvas element behind the game objects for effects and other drawing procedures including pixel perfect collision detection.

During the course of prototyping several options for good game performance on a variety of mobile browsers, I have found that the DOM animates better than canvas. Canvas works great on the desktop though, so if you do any benchmarking, make sure you have several mobile devices to test with. I used a Samsung Galaxy S2x, Blackberry 9800, iPhone 3g, iPhone 4, iPad 2 and iPad Mini 2 for my testing.

What I found was that for simple animations like this mobile performance was just not smooth enough. If I’m going to put in hours of my own time to develop a game, I want to reach the widest possible audience. Limiting devices limits audience and is a large barrier to getting uptake on a game.

So, with that said…

Let’s build something, already! (I expect you will know basic javascript and html in order to follow along with this tutorial).

Prototyping with JS Bin

I almost always start a concept with JS Bin. The ability to quickly prototype something is key when trying out new ideas for game. There are other options, but I like the responsiveness of JS Bin and the column layout fits my likes.

So, lets jump over to JS Bin and start a new Bin and using the “File” menu, add a description. I’ll just title mine “Sample HTML5 Game”.

The first thing we need now, is to add a few libraries. From the “Add Library” menu on the top left of JS Bin, add jQuery (I’m using 1.9.1) and GSAP 1.11.7.  We will use jQuery for DOM manipulation and selection while GSAP (Greensock Animation Platform) will be used for the animation. GSAP is key here, as it outperforms everything else I’ve tried to date.

Ok, we have jQuery and GSAP libraries added, so lets add something to start with. Add the following to the body  tag in the HTML tab.

This will give us a launching point. We should probably style this too. I like to put a background or border around my staging area so I can clearly see when objects are inside or outside of my boundaries. In the CSS tab, let’s add this:

Pretty straight forward.This is what you should be looking at so far.

The game I have in mind is a hybrid tower defense/infinite runner type game. Enemies constantly come at you from the top of the game screen and you have to put defense obstacles in their path to defeat them. This will call for an enemy object, a defense object and projectile of some sort. Let’s just call it a bullet for now. You can rename it to missile, spear, javelin or laser beam later on.

Let’s add the following CSS:

What I have here is a 25 by 25 pixel black square that should show up nicely against my light grey back ground. I’ve made the defense object white so I can easily tell it apart from my enemy objects and the bullet is also black. All of my position is absolute, as games will need a definitive X-Y coordinate space for calculations further on.

Now, I wanna see something move!

Setting the stage.

GSAP is really a pleasure to work with. I enjoy the simple, straight forward way it provides to quickly animate objects.

First, I will need to put some objects on the screen. Let’s add 5 enemy objects the to top of the screen and animate them in a straight line to the bottom. We will actually start above the stage and end below the stage so the objects have the appearance of entering and leaving our stage area.

First thing I usually do is cache my stage object with jQuery, like so:  var $stage = $("#stage");  Now let’s add a simple for  loop to add a few enemy objects to the stage.

This is just a simple loop with 5 iterations. In each iteration, we will add a new object to the stage area. We will need to keep track of the last enemy position so we don’t just have them stacked on top of each other. Let’s add a few variables along with our $stage  variable. Our JS tab should now look like this:

Dropping the enemies onto the stage will consist of creating a DIV  with the class of .enemy  and appending it to the stage. We can utilize jQuery here to do that for us:

For those of you not familiar with jQuery, we usually name jQuery object variables with a $ to denote the variable holds a jQuery object. It helps with code readability but this is not a requirement. Also, for those new to jQuery, let me break this code down for you.

We start by creating a jQuery object with $("<div />") . This gives us an empty DIV  element. jQuery allows us to chain function calls together. Each function typically returns the object itself, so we can just keep chaining functions together. After we create the object, we add a call to the function addClass  which adds the .enemy  class we styled in CSS earlier. Finally, we chain on a call to the function appendTo giving it a parameter of our $stage  object. This will append (add) our DIV  to the $stage .

Lastly, we increment our enemyX  variable by 30 pixels to ensure our enemies have some breathing room. In JS Bin, click the “Run with JS” button to see the enemy objects appear on the stage.

At this point, we can see our objects, so let’s modify our enemyY  variable to -25  so our starting position is above the stage.

Animating with GSAP

Now that we have some enemy objects on the screen, let’s animate them! We will create a function named animateEnemy that takes a jQuery object as a parameter. So our function signature will look like this:  function animateEnemy($enemy){ }

Now, we need to add a call to GSAP. The documentation for the TweenMax library is here, but we are going to use the TweenMax.to  function which is fairly simple so let me break it down for you.

TweenMax.to( target:Object, duration:Number, vars:Object ) : TweenMax

[static] Static method for creating a TweenMax instance that animates to the specified destination values (from the current values).

We just need to pass it our jQuery object, an integer for the total animation time in seconds and a javascript object with the ending values of our animation. It will look like this:

In this code, we call the TweenMax library’s to  function, saying this: Animate object $enemy  over a total period of 4 seconds from its current location to the location y:325 . As we didn’t specify an X value, the object only moves on the Y plain, or in this case, straight down.

We can now go back up to our javascript loop and add in on the bottom a call to our animateEnemy function like so:  animateEnemy($enemy);

At this point the code listing should look like the below and when you hit the “Run with JS” button the five enemy objects move down the stage.

This is fine and dandy, but we probably want our enemies to appear at different times, so let’s refactor the loop body to use a setTimeout function call to add a delay between our enemies. I’m going to move all the code from the loop body into a function called  createEnemy() and add this to our loop body:  window.setTimeout(createEnemy,1000*i);

Now we have this:

We multiply one second by our loop variable (1000*i) to create a pause between the enemies.

Now, we should add our defense object. We can copy the code we used to create our enemy object and replace a few values. Let’s add a function createDefense with parameters X and Y.

And then call it from the top of our page, right after our variables declarations like so:  createDefense(100,220);

Right after our added call to createDefense , let’s add another call, using the window.setInterval  function, to a method we will call fireBullet .

For this method, we are going to need another library. We are going to utilize a library called jquery-nearest to find the closest enemy to our defense at a given point in time. Using the Github raw link, paste the source code of the library into a <script></script>  tag on our HTML tab. You can also start editing from here if you wish.

Let’s fill out our fireBullet function like so:

First, we cache our defense object in a variable $d , then we create a bullet object exactly like our enemy and defense objects and append it to the defense object. Next, we use the jquery-nearest plugin to get the closest .enemy  object and store that in variable $e . Lastly, we call a new function animateBullet  to animate the bullet. It looks very similar to animateEnemy  with a few more parameters. We can refactor these into a single function later on.

At this point, we can see the basics mechanics of the game. The enemies come down from the top and our defense starts firing away. I’ve added some very rudimentary methods of calculating where the enemy will be when the bullet arrives. You can brainstorm on better ways to accomplish this.

In the next tutorial, I will cover collision detection and using the GSAP Draggable plugin to round out the game by removing enemies hit by our defense and dynamically adding defense to the stage. In another tutorial, I will attempt to cover more topics that will help polish the game by adding better graphics and putting a canvas object behind the stage to allow for particle effects, etc.

I hope you enjoyed this short tutorial and please let me know what you think in the comments below.

You can continue on to Part 2 here or discuss in the forums.

 

 

agrothe (9 Posts)

Andrew Grothe is an enterprise developer with an interest in HTML5 mobile and game development. Andrew is current working on a casual HTML5 game at http://spacecutegame.com and maintains the http://webapplist.info website.