Tag Archives: HTML5

Commandos: BEL – HTML5 – Recreating the classic 2.5D real time tactics game in the browser

After my last game recreation project, Command and Conquer in HTML5 (a complete real time strategy game with multiplayer implemented in HTML5), I was looking for a new and bigger challenge.

My most recent project, a recreation of Commandos: Behind Enemy Lines in HTML5, makes Command & Conquer feel like a kiddie project.

While Command & Conquer took me around three weeks for a first version, and then a couple of months of iterating to create the polished version that it is today, Commandos has been 8 months of slogging just to get the first working game level out.

Every few weeks into the project, I would reach a point where I would think “There is no way I am going to be able to do this bit. I have no idea how to…”, and a few days later, magically, I would find just the thing that I needed to get it done.

Over this period, I’ve gone through what feels like hundreds of articles and computer science Phd papers on path-finding, handling polygons, depth sorting and various aspects of game artificial intelligence.

This has honestly been one of the toughest projects I have ever taken on by myself. Looking back, I have no idea how I ever came this far. In fact, I am amazed that I actually managed to complete this project.

Here is a quick video of the project.

But what really made this project so hard?

I consider Commandos: Behind Enemy Lines a 2.5D, real time tactics game.

What the 2.5D means is that while the game used 2D assets and images, all the game elements contain 3D position information (x, y and z coordinates) as well as shape information (length, breadth, height). This simple difference however brought on most of the challenges that I had to face.

The first and biggest challenge while recreating the game was just rendering everything onto the screen. C&C was entirely 2D, so depth sorting was as simple as drawing everything from back to front and left to right, and everything just looked more or less OK.

Depth Sorting in Commandos HTML5

Depth Sorting is so simple with these blue lines

However with Commandos, things got a lot more complicated. Game elements are not positioned along the X & Y axis, and can overlap each other in very different ways, making depth sorting slightly more challenging.

I tried several different implementations. With each implementation, I would find some items rendered correctly, while others would render incorrectly.

After tons of research and experimentation, I finally managed to come up with a reasonably simple and elegant solution – First do a simple comparison to decide whether or not each item is in front or behind every other item, then run a topological sort to order the items for rendering. The image shows how I use a simple line across each item to decide whether another item is ahead or behind. As you can see, the results are pretty decent.

Commandos HTML5 Path Finding

Pathfinding  using a mesh of polygons

The next big challenge was path-finding. Unlike C&C and it’s simple grid based A* path finding, Commandos uses a polygon based mesh and needs some pretty flexible pathing. I originally started with a simpler implementation using points-of-visibility pathing, however I finally had to switch to a full-blown navigational mesh with path smoothing to allow for everything that commandos needs, such as climbing up ramps and traveling across bridges.

Again, everything had to implemented from scratch and I didn’t use any libraries for it.

Commandos HTML5 Guard AI

Guard AI – Guards follow footsteps in the snow

The next big headache was the guard AI.

The guard vision and visibility cone computations needed to be fast and optimized since they were calculated in real time so they could be used to decide when a guard could see something.

That, combined with a very tricky AI involving some crazy state flip-flopping, meant it took me a couple of months before the guards could even see and attack a commando properly.

At this point guards can patrol or watch areas, investigate suspicious noises (explosions, gunshots, yelling), follow foot steps, and finally chase commandos and attack or detain them.

Apart from these were all of the little things that I never thought would take much time, which in hindsight turned out to not be so little and took quite a lot longer.

Climbing Walls - Who thought this would be so hard

Climbing Walls – Who thought this would be so hard

  1.  Building a complete in-game multi-window system.
  2.  Teaching the commando how to climb walls (starting with detecting whether a surface was climbable).
  3.  Building a very intricate game loader system that handled mission files, sprite sheets, audio sprite sheets and the in-game menu files
  4.  A custom in-game menu system.
  5. Handling Weapons, Driving vehicles, Rowing boats, Scuba diving, Explosions, Using Decoys, Hiding inside buildings and every other action the commandos can take.

After 8 months of work, I’m happy to say the game is now finally ready and playable.

If you haven’t tried it out yet, you can play Commandos: Behind Enemy Lines – HTML5 here.

Looking back, I don’t know if I regret taking on this project. Thanks to this project, I’ve learned an incredible amount – about  computer science and AI, about better game programming techniques and practices, about automating and streamlining my entire game development process. But the biggest thing I learned was what it takes to build a really big game in HTML5, and how to push myself to achieve something that I never thought possible.

Now that the first mission is finally complete, I’ll probably take a break for a while. Once I come back, the plan is to add more missions, and a multi-player cooperative mode using HTML5 Websockets. Again, all playable in your browser without needing any installation.

If you have any feedback or questions about this project, please feel free to leave a comment below or on the game page.

If you would like to get notified about future game projects, get exclusive access to beta test new project updates, or learn advanced game programming and collaborate with me on future projects, please sign up using the form below. Make sure you fill out the check boxes correctly so I know what you are interested in.

* indicates required

Which of these do you want to do?

HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

When I started developing the HTML5 version of Command and Conquer, I never expected more than a few close friends to look at the game. (Based on the experience with my last game, Breakout).

Command and Conquer Javascript ScreenshotSo while I spent a lot of time making the game look as close to the original Command and Conquer as possible, I never spent much time optimizing the code. Most of my development and testing was on my own Macbook, and I didn’t pay attention to the image loading time or network traffic.

Unfortunately, this game uses a lot of images.

Each unit can face 32 different directions. This means at least 32 different images for each unit (more if there are animations like ‘harvesting’).

Buildings need a whole set of images for each state – under construction, regular – with different sets of images for healthy and damaged buildings, and for any additional states (like ‘unloading a harvester’). The Construction Yard for example needs 82 different images for it’s animations.

As a result, when the game loaded, it made nearly 1,000 HTTP requests to load all the assets (including images and sounds).

Since most browsers only make a few simultaneous requests at time, downloading all these images took a lot of time, with an overload of HTTP requests.

While this wasn’t a problem when I was testing the code locally, it was a bit of a pain when the code went onto the server. My patient friends ended up waiting for the game to load for 5-10 minutes (sometimes longer) before they could actually start playing.

AdityaRaviShankar.com - Traffic Screen ShotThe problem came when my game hit the front page of Hacker News and Wired.com on the same night, resulting in a slight spike in traffic :). It then got worse when the game got 1,000+ tweets and 1,000+ FB likes in just a few hours. The last time I checked, searching for my game gave over 5,000 google results.

What this meant was my shared hosting server was getting close to 14,000,000 HTTP requests in one day from just my domain.

I don’t think too many shared hosts are designed to take this kind of load, which resulted in my account being disabled with this interesting email from my provider.


Your account adityaravishankar.com on the server quebec.unisonplatform.com was recently found to be causing high load that resulted in slowness/outages of various system services. In order to ensure quality of service to the other clients on this server we regret to inform you that the account had to be disabled to prevent any further interruption of service to our other clients.

If nothing can be done to lower the resource usage you may need to look into purchasing a dedicated server or cloud server which you can find more information about at http://www.eleven2.com. Please contact us as soon as possible to resolve this issue.

I was able to find temporary hosting on another server but the biggest priority was to optimize the way I stored images, which of course brings us to sprite sheets.

Hand of Nod Sprite SheetSprite sheets store all the sprites for an object in a single large image file.

When displaying the images, we calculate the offset of the sprite we want to show and use the ability of the drawImage() method to draw only a part of an image.

Creating these sprite sheets is incredibly simple using ImageMagick’s montage command line tool. This single command will convert a folder full of images into a single row sprite sheet.

After comparing PNG and GIF, I found that PNGs tend to compress the sprite sheets a lot more.

The advantages of using Sprite Sheets?

  1. Fewer HTTP requests – The Command Center went from 81 requests to a SINGLE HTTP request
  2. Better Compression – An advantage of storing the images in a single file is that the header information doesn’t repeat and the combined file’s size is much smaller than the sum of the individual files. The command center went from 496KB in 81 files to only 37KB in a single file. (Less than 8% of the original size, which is incredible)
  3. Easier Manipulation – With all the sprites in a single image file, it became easier to do RGB color manipulations, and I was able to optimize the drawing code for performance.

From almost a 1,000 requests to 120 requests in one simple code rewrite. And the total download size went from a few MBs to around 200KB.

Game load time went from 10+ minutes to under a minute. The bandwidth usage dropped to a tenth of the original. The number of requests dropped to a tenth of the original. And now my shared hosting can survive a very decent amount of traffic.

Moral of the story? When developing a large game that is image heavy, track your network usage and when possible use sprite sheets 🙂

Command and Conquer – Programming an RTS game in HTML5 and Javascript

After writing my first HTML5 game I decided to take on a more challenging project.

Command and Conquer Javascript ScreenshotMy latest project is a recreation of the original Command and Conquer entirely in HTML5 and Javascript.

Command and Conquer is the grand-daddy of all Real Time Strategy games and is probably the game that made the genre popular. My friends and I spent countless hours playing the original as well as subsequent sequels (Tiberian Sun, Red Alert).

Check out the demo video.

You can play the actual game here. Command and Conquer – HTML5 version

This project was a lot more challenging than my previous game, Breakout. In hindsight, I might have wanted to take smaller steps and make a tower defense game instead of jumping directly into an RTS.

Creating even this simple version of the game covered a lot of things.

  1. Using images to recreate the sidebar and game interface.
  2. Using mouse input for unit selection, panning, attacking and user input
  3. Using images as sprites for unit and building animation, and using sprite sheets for better performance
  4. A lot more sounds for units and buildings
  5. Using a finite state machine for handling unit commands, movement, attacking etc.
  6. Using path finding (A*) to navigate around obstructions like buildings, mountains and trees
  7. Using hidden canvas’s for things like fog of war and image manipulation

Obviously because of the size of the project, trying to do the whole thing in under a month all by myself wasn’t the smartest idea. I ended up spending lots of 18 hour work days during this time.

I used to switch between playing the original Tiberian Dawn in a Wine window on my Mac and my JS version on the browser to make sure my version looked EXACTLY like the original. I spent a LOT of time going through C&C forums to understand how to reverse engineer the Tiberium Dawn files to extract the building/unit sprites and audio and reading up on unit specs to figure out how to make the units behave exactly like the original.

Every little thing took time – things like selecting single units, multiple units, being able to select by drawing the box from left to right or from right to left; making sure the panning was smooth; Figuring out a decent fog of war implementation; Allowing for building construction, dependencies (Power Plant needed for Refinery, which is needed for Factory), building placement (buildings cannot be constructed on top of other buildings); Depth sorting when drawing so units could move behind buildings and trees.

The next big headache was smooth unit movement. I wanted to do better than the original game, and spent a lot of time going through Starcraft 2 videos to see if I could get a smoother movement closer to the way SC2 handles it. Pathfinding using A* can do some of the work, but gives a clunky movement and causes units to take behave badly/take longer routes when going through bottle necks. I decided to mix A* with a repelling force/steering behavior to improve it. It still has some bugs I need to work out.

I had to fine tune the way units behaved (during patrolling, guarding, attacking). Even the fact that a MCV couldn’t attack and turned into buildings.

Harvesting was a whole different pain in the ass since my collision detection and steering code meant my harvester was initially afraid to return to the refinery :).

While a lot of people have been giving me props for just getting this project out, one of the things that I am proud of is that I completed the first version in around 3 and a half weeks, all by myself.

For people who have been criticizing this project, I’ll say this – “I did this, entirely on my own, unpaid, in three and a half weeks – including one week where I had a fever. Give me a break. It isn’t that bad :)”.

The current iteration of the project contains several levels from both GDI and NOD campaigns. I am also currently testing multiplayer using Node.js, which should be coming soon.

Check out the video demo of the new version of this game that I am working on.

This game has got a lot of attention from online media and FB/Twitter/Google+. The extra traffic brought my server down on its knees and got my account temporarily suspended. This forced me to optimize the game using sprite sheets so it could handle requests more efficiently. You can read more about the whole story here – HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

Real Time Strategy Game - Pathfinding, Collision Detection & Steering Demo - ScreenshotAfter lots of feedback, I’ve specifically researched and worked on improving the pathfinding of the game. Check out the Pathfinding, Collision Detection & Steering Demo. This is a demonstration of the improved unit pathfinding and movement/steering strategies used in RTS games. Units use A* to plot a path and avoid collision using a ‘soft collision’ radius. They also ask static units to move aside.

Here is a video demonstrating all the features of the new pathfinding code.

Check out the demo here. Switch on “DEBUG MODE” to see how it works. This is still a work in progress. Any comments or feedback (including bugs), is appreciated.

Check out some of the HTML5 games I have written. If you are just starting out with game programming, check out my earlier tutorial on developing a simple Breakout game in HTML5.


ANNOUNCEMENT: My Book, Pro HTML5 Games is out!!!

Pro HTML5 Games - Aditya Ravi ShankarA lot of people have been asking me for details on how I built the HTML5 version of Command and Conquer.

Based on my experience developing this game, I have just written a book showing readers how to build a complete RTS game in HTML5.

My book, Pro HTML5 Games takes readers through the process of building two complete games – a Box2D Engine based Angry Birds clone and a realtime strategy (RTS) game with multiplayer support.

This book is now available for purchase at Amazon (Pro HTML5 Games on Amazon), Barnes & Nobles (Pro HTML5 Games on Barnes & Noble) as well as the Apress Site (Pro HTML5 Games on Apress).

If you are interested in building professional looking HTML5 games, you should check the book out.

If you know anyone who would be interested in this book, please do share this book URL (//www.adityaravishankar.com/pro-html5-games/) with them.

Read more details about Pro HTML5 Games here.

HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

Breakout v0.6 ScreenshotThis is the third in a series of tutorials on developing a full featured version of Breakout.

In the second tutorial, we used setInterval() to add some animation and capture keydown and keyup events to respond to user input.

In this tutorial, we will bring back the bricks we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed. We will also add some sound effects to make the game more fun.

We will use the code from the last tutorial as our starting point.

Lets get started.

First we add back two lines at the beginning of the animate() function to draw the scoreboard and the bricks.

Right now the ball will move over the bricks without bouncing off them.

We need the ball to reverse X direction if it hits the sides of the bricks, reverse Y direction if it hits the top or bottom of the bricks and damage the bricks every time it touches them.

Lets create functions to check whether the ball is colliding with a brick along the X or Y direction, and to damage the brick if it collides.

The collisionXWithBricks() and collisionYWithBricks() functions return true when they bounce against a brick and automatically call explodeBrick() to weaken the brick and update the score. To start using these functions, we modify the collision checking conditions in moveBall() slightly.

At this point, the ball bounces off the bricks as expected and weakens the brick when it hits them. Once the brick is completely destroyed, it disappears and gives the player an extra points.

Not bad. The game works fine, however there is still something missing.

A little sound tends to give players a much more immersive experience and will make the game more fun. With HTML5 Audio, implementing sound is surprisingly easy.

To play sounds, we load files using the Audio() object and play them using its play() method. Browsers are still a little inconsistent about which formats they support. The OGG file format is an open format supported by both Chrome and Firefox (my favorites), which is why we will stick with them for now.

To create the sound we place the two files at the same location as the HTML file and load them by creating new Audio() objects and storing them in variables. The OGG sound files used here are included with the source code.

To play these sounds, all we need to do is invoke the play() method.

We can play the breaking sound whenever a brick is completely destroyed (inside the explodeBrick() function).

And the bounce sound anytime we change X or Y direction for the ball (inside the moveBall() function)

That’s really all there is to it. We have a game with sound effects, animation, keyboard control and increasing scores written entirely in HTML and Javascript.

To make the game more fun, we can add more interesting brick types, sounds and game mechanics.

In my version of the game, the bricks start falling down, we have Cash bricks to give money, Bomb bricks that explode everything nearby, Laser Ammo bricks that let us shoot laser from the paddle and Spider bricks that shriek and start crawling down at the user. Check out the game to see what you think. Leave a comment if you enjoy the game.

I don’t see much point showing people how to implement the exact same features in a game, because at this point it is fairly simple to do. However if you have an interesting idea that you would like to add to the game, leave me a comment below. If we get a few interesting ideas, we can have one more tutorial where we implement the ideas and create our own new version of the game.

If not, stay tuned to learn how to implement a Real Time Strategy game engine entirely in HTML5 and Javascript. Check out Command and Conquer – Programming an RTS game in HTML5 and Javascript.

You can download the finished source code for this tutorial below.

HTML5 Game Development Tutorial: Breakout Part I – Introduction to Canvas

Breakout v0.6 ScreenshotThis is the first in a series of tutorials on developing a full featured version of Breakout. This tutorial will cover drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

Before we get started, check out the finished Breakout game demo. With flying bats, falling spiders, laser turrets and exploding bricks, its probably a little different from the typical breakout game. We will be recreating this game over the series.

All of our development will be for HTML5 capable browsers that properly support the HTML5 Canvas and Audio tags (Chrome, Safari, Firefox, Opera and maybe Internet Explorer 9). Make sure you have one of these browsers.

Now let’s get started.

First we create a simple HTML file with a canvas inside it.

We also include jQuery to make cross browser development easier.

To start using the Canvas we need to get its 2d context which then gives us access to all the drawing methods we need.

With this context object, we now have access to the methods that we will need for our game like fillRect(), clearRect() and drawImage().

Now that we can draw, lets start with creating the paddle.

Note that we store all the parameters in variables so that we can easily modify and reuse them later. Drawing the paddle is as simple as using the fillRect() method.

Now lets draw the ball.

Drawing the ball requires the arc() method to draw a circular shape and the fill() method to fill the shape we just created. While drawing the arc, the starting angle is 0 and the ending angle is 2xPI radians (or 360 degrees) which makes a full circle.

Now lets draw the bricks on top.

First we store the bricks layout in an Array making it easier to visualize and modify. Feel free to try adding a few more rows, or changing the numbers to modify the layout.

We then iterate over each row and column and call the drawBrick() method to place the brick correctly. Within drawBrick(), we use a switch statement to set different fill colors for different types of bricks. This function can be extended to add more brick types.

Finally, lets create a simple scoreboard or status bar below.

This uses the fillText() method to write text at the bottom of the canvas.

We can check the output of the code so far by calling each of the functions that we wrote.

Breakout - Tutorial 1 - ScreenshotThis is the final result. We have a complete game screen with all the elements drawn on it programmatically – the bricks, the paddle, the ball and the scoreboard.

It doesn’t seem like much yet. Everything is static. However, because we stored the parameters in variables, all we need to do to move objects around is change the parameter values and call the same functions again. Thats when things start getting interesting.

In part II of this series, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input.

You can download the finished source code for this tutorial below.

Continue to part 2 of this series. HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

Javascript Game Development with HTML5 Canvas – Breakout released

Breakout v0.6 ScreenshotI started working on my version of the Breakout game as a simple exercise to learn Javascript game programming, using HTML5 Canvas for animation.

The way I see it, Breakout is the “Hello World” of Game development. Pretty much everyone does it when they want to learn the basics. It is probably one of the simplest games to develop though you can choose to make this exercise as easy or as challenging as you like.

In the process of building even the simplest versions of this game you learn most of the essential fundamentals for building any Javascript game, namely –

  1. Drawing primitive objects on the screen using the Canvas element and its Context. (See Introduction to Canvas Tutorial)
  2. Moving objects by using clearRect() and redrawing the object. (See Animation and Keyboard Input Tutorial)
  3. Using setInterval() and setTimeout() to animate objects and run a game loop. (See Animation and Keyboard Input Tutorial)
  4. Capturing keypress, keydown and keyup events and responding to user input. (See Animation and Keyboard Input Tutorial)
  5. And finally rudimentary collision detection. (See Collisions, Scoring and Sound Tutorial)
 If you then decide to put in a little more effort, you also learn –
  1. Using HTML5 Audio for sound effects. (See Collisions, Scoring and Sound Tutorial)
  2. Using bitmaps with drawImage() for better looking graphics.
  3. Animating arrays of objects simultaneously, each with their own life cycle (like bullets)

I expected this game to be a quick learning experience with limited playable value. I never expected the game to be as much fun as it is. Once I decided to put the game up on my website, the positive feedback that I got was  very heartening.

Based on feedback, I have decided to continue adding features and developing the game. If you are interested in game development and the making of this game, you can check out the tutorial series on developing Breakout.

The latest version of the game is available at the Breakout Game page. Please check it out and let me know whether you like it. I would appreciate any suggestions or constructive criticism (as a player or as a developer) – Any bugs or any playability issues that you find.

If you like the game, please do let me know, and do share it with all your friends. You can use the comments form on the game page.