Build Your First Game With HTML5

HTML5 is growing up faster than anyone could have imagined. Powerful and professional solutions are already being developed...even in the gaming world! Check out the hundreds of HTML5 games on Envato Market.

Today, you'll make your first game using Box2D and HTML5's canvas tag.


What is Box2D?

Box2D is an open source and popular engine that simulates 2D physics for making games and applications. Primarily written in C++, it has been converted to numerous languages by community contributors.

With the same methods and objects, you have the ability to make your games' physics in many languages, such as Objective C (iPhone/iPad), Actionscript 3.0 (Web), HTML 5 (Web), etc.


Step 1 - Setting up your Project

To begin developing your demo, download the Box2D engine for HTML5 here. Next, create a new HTML file with the following structure (copy js and lib directories from box2d-js project to your game folder).

Now, you must insert the necessary files to run box2D into your HTML file:

Yep, that's a huge number of HTTP requests!

Please note that, for deployment, it's highly recommended that you concatenate all of these resources into one script file.

Next, create two more scripts inside the /js/ folder, called "box2dutils.js" and "game.js".

  • box2dutils.js - it's a copy and paste from some demos that come with box2dlib, and is important for drawing functions (I will also explain some important parts here).
  • game.js - the game, itself; this is where we create the platforms, the player, apply the keyboard interactions, etc.

Copy and paste the following code into box2dutils.js. Don't worry! I'll explain it bit by bit!


Step 2 - Developing the Game

Open the index.html file that you previously created, and add a canvas element (600x400) within the body element. This is where we'll work with the HTML5 drawing API:

Also, while you're here, reference game.js and box2dutils.js.

That'll do it for the HTML! Let's work on the fun JavaScript now!

Open game.js, and insert the code below:


Box2DWorld - that's why we're here

Okay, let's figure out what this chunk of code does!

Box2DWorld is one of the classes that is made available, via the core of box2d. Its function is simple: combine everything into one class. In box2DWorld, you have the bodies definition and collisions manager of your game or application.

Keep the game.js and box2dutils.js files open, and search for the createWorld() function within box2dutils.js.

It's quite simple to create the box2DWorld.


Back to game.js

Refer to the commented numbers in the two blocks of code above. On number two, we retrieve the canvas element's context by using the selector API (looks like jQuery or MooTools selectors, don't they?). On number three, we have a new interesting function: initGame(). This is where we create the scenery.

Copy and paste the code below into game.js, and then we'll review it together.


Box2DBody

A Box2DBody has some unique characteristics:

  • It can be static (not affected by collisions impacts), kinematic (it isn't affected by collisions, but it can be moved by your mouse, for example), or dynamic (interacts with everything)
  • Must have a shape definition, and should indicate how the object appears
  • May have more than one fixture, which indicates how the object will interact with collisions
  • Its position is set by the center of your object, not the left top edge as many other engines do.

Reviewing the code:

  1. Here, we create one shape definition that will be a square or rectangle, and setup its density (how often it gonna be moved, or rotate by forces).
  2. We setup the userData, usually you setup graphics objects here, but in this example, I just setup strings that will be the identifier of the type of the object for collisions. This parameter doesn't affect physics algorithms.
  3. Setup half of the size of my box (it's a line from the position point, or the center point of the object to a corner)
  4. We create the body definition, and add to it the box shape definition.
  5. Setup the position.
  6. Create the body in the world and return its value.

Creating the Player Ball Body

I've coded the player (ball) directly in the game.js file. It follows the same sequence of creating boxes, but, this time, it's a ball.

So how do we create a body, step by step?

  1. Create the shape, fixture and sensor definition
  2. Create the body definition
  3. Add into the body your shape, fixtures or sensors (not explained in this article)
  4. Create the body in the world

Box2DCircle

As I noted earlier, this follows the same creation process of a box, but now you must set some new parameters.

  • radius - This is the length of a line from the center of the circle to any point on its edge.
  • restitution - How the ball will lose, or gain force when collides with other body.
  • friction - How the ball will roll.

Box2DBody - More Properties

  • damping is used to reduce the velocity of the body - there's angular damping and linear damping.
  • sleep in box2D, bodies can sleep to solve performance issues. For example, let's suppose you are developing a platform game, and the level is defined by a 6000x400 screen. Why do you need to perform physics for objects that are off screen? You don't; that's the point! So the correct choice is to put them to sleep, and improve your game's performance.

We've already created our world; you can test the code that you have so far. You'll see the player falling above the west platform.

Now, if you tried to run the demo, you should be wondering, why is the page as barren as white paper?

Always remember: Box2D doesn't render; it only calculates physics.


Step 3 - Rendering Time

Next, let's render the box2DWorld.

Open your game.js script, and add the following code:

What we accomplish here:

  1. Instructed box2dWorld to perform physics simulations
  2. Cleared canvas screen and draw again
  3. Execute the step() function again in ten milliseconds

With this bit of code, we are now working with physics and drawing. You can test yourself, and watch for a falling ball, as demonstrated below:


drawWorld in box2dutils.js

What we've written above is a debug function that draws our world into the canvas, using the graphics API provided by HTML5's Canvas API.

The first loop draws all joints. We didn't use joints in this article. They are a bit complex for a first demo, but, nonetheless, they're essential for your games. They allow you to create very interesting bodies.

The second loop draws all bodies, which is why we're here!

We're looping through every vertices of the object and drawing it with lines (context.moveTo and context.lineTo). Now, it's useful to have an example... but not so useful in practice. When you use graphics, you only need to pay attention to the bodies' positioning. You don't need to loop vertices, as this demo does.


Step 4 - Interactivity

A game without interactivity is a movie, and a movie with interactivity is a game.

Let's develop the keyboard arrow functionality to jump and move the ball.

Add the following code to your game.js file:

With handleKeyDown and handleKeyUp, we setup an array which tracks every key the user types. With document.onkeydown, we disable the browser's native vertical scrolling function for up and down arrows. Have you ever played an HTML5 game, and when you jump, the player, enemies and objects go off screen? That won't be an issue now.

Add this next bit of code to the beginning of your step() function:

And outside, declare the function:

The most complicated piece of the code above is the first one, where we check for a collision, and write some conditions to determine if the shape1 or the shape2 is the player. If it is, we verify if shape1 or shape2 is a ground object. Again, if so, the player is colliding with the ground. Next, we check if the player is above the ground. If that's the case, then the player can jump.

On the second commented line (2), we retrieve the LinearVelocity of the player.

The third and forth commented regions verify if arrows are being pressed, and adjust the velocity vector, accordingly.

In the fifth region, we setup the player with the new velocity vector.

The interactions are now done! But there's no objective, We just jump, jump, jump… and jump!


Step 5 - "You Win" Message

Add the code below to the beginning of your LinearVelocity function:

  • The first condition determines if the player falls, and should be transported back to the start point (above the west platform).
  • The second condition checks if the player is above the second platform, and won the game. Here's the showWin() function.

And that's it! You've just completed your first simple game with HTML5 and Box2D. Congratulations!

If you need a simpler solution, you could check out the selection of HTML5 games on Envato Market, many of which come with source code for you to investigate and customize to fit your own needs.

Tags:

Comments

Related Articles