Control mechanisms in JavaScript games

Laptops, computers, smartphones, tablets, TVs, even fridges have one thing in common — they can probably run a browser, so you can probably play an HTML5 game on them. Rendering the game on screen is one thing, but you also have to control it somehow, and there are plenty of different options suited for various platforms. From touch, through mouse and keyboard, to gamepad, even a TV remote or … bananas — these interfaces are covered in a series of new articles about control mechanisms now available on MDN.


To showcase their real-life use in a project, these control mechanisms are implemented in the Captain Rogers: Battle at Andromeda demo game built with Phaser, so you can see how the gameplay is affected by the platform. You can also see that you don’t need separate builds dedicated to different platforms — the multi-platform nature of the Web can help you adjust the controls to the device the game is played on without much coding effort.


There’s a small pure JavaScript controls demo open-sourced on GitHub, so you can exactly see how those mechanisms were implemented, and try it yourself in your own gamedev project. Dive into the code right away, or follow the highlights of the key parts below.

Mobile touch

Let’s start with mobile touch support due to the popularity of the mobile first approach in HTML5 games:

document.addEventListener("touchstart", touchHandler);
document.addEventListener("touchmove", touchHandler);
function touchHandler(e) {
    if(e.touches) {
        playerX = e.touches[0].pageX - canvas.offsetLeft - playerWidth / 2;
        playerY = e.touches[0].pageY - canvas.offsetTop - playerHeight / 2;

Those few lines of JavaScript code are all you need for very basic touch controls in your game, so it can be played on mobile devices. The first two lines set up event listeners for the touch events we are interested in — when you touch the screen, and when you slide your finger across it. The function checks if any touches are performed, and then sets the player’s coordinates so the ship can be rendered in the right place on the game Canvas.

Those are just the basics, and you can (and should) expand the possibilities, for example implementing multi-touch or gestures. It all depends on what type of game you have, and what should be controlled (and how). You can also offer on-screen buttons to perform given actions, for example movement arrows and a shoot button. See the Mobile touch controls article for more details.

Desktop mouse and keyboard

Since we’re speaking of “movement arrows”, you can print them on screen for mobile devices, but you can implement them for desktop too. Cursor keys or WASD keys are popular ways of moving a character in the game. For example the case below handles the cursor keys:

document.addEventListener("keydown", keyDownHandler);
function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    else if(e.keyCode == 37) {
        leftPressed = true;
    if(e.keyCode == 40) {
        downPressed = true;
    else if(e.keyCode == 38) {
        upPressed = true;

It’s all about constantly detecting and then saving information about which key was pressed, so it can be processed in the drawing loop:

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    if(rightPressed) {
        playerX += 5;
    else if(leftPressed) {
        playerX -= 5;
    if(downPressed) {
        playerY += 5;
    else if(upPressed) {
        playerY -= 5;
    ctx.drawImage(img, playerX, playerY);

The player’s x and y position variables are adjusted and then the image of a ship is built out in the new spot.


Desktop mouse and mobile touch are very similar from a coding point of view: all you need to do is to get the info on where the touch or click occurred and update the player’s position:

document.addEventListener("mousemove", mouseMoveHandler);
function mouseMoveHandler(e) {
    playerX = e.pageX - canvas.offsetLeft - playerWidth / 2;
    playerY = e.pageY - canvas.offsetTop - playerHeight / 2;

The mousemove event is detected, and the player’s position is adjusted to place the ship in the middle of the mouse’s pointer whenever it changes. That’s all it takes to make your game playable on desktop using both keyboard and mouse — for more details see the Desktop mouse and keyboard controls article.


My favorite controller — I use the Gamepad API to control all my HTML5-based slides during presentations. I’ve talked about it a few times, written a couple of articles, implemented some games, and included all the relevant info in the Gamepad API Content Kit. It’s really awesome that we’re able to feel the console experience on a computer, and it works thanks to Web technologies! Playing Captain Rogers with a gamepad enriches the experience and just feels a lot better.


Covering Gamepad API support is a little bit more complex than touch or keyboard, but still quite straightforward:

window.addEventListener("gamepadconnected", gamepadHandler);
function gamepadHandler(e) {
    controller = e.gamepad;
function gamepadUpdateHandler() {
    buttonsPressed = [];
    if(controller.buttons) {
        for(var b=0; b<controller.buttons.length; b++) {
            if(controller.buttons[b].pressed) {
function gamepadButtonPressedHandler(button) {
    var press = false;
    for(var i=0; i<buttonsPressed.length; i++) {
        if(buttonsPressed[i] == button) {
            press = true;
    return press;

When the gamepad is connected, an event is fired so we can get the reference to its data in a variable that we will use later on. On every update, a new array of pressed buttons is created so the current state is always the latest. There’s also a function that will loop through that array to see if a specific button we are interested in is pressed. This information can then be used in the drawing loop, in a similar fashion to the keyboard check:

function draw() {
    // ...
    if(gamepadButtonPressedHandler(0)) {
        playerY -= 5;
    else if(gamepadButtonPressedHandler(1)) {
        playerY += 5;
    if(gamepadButtonPressedHandler(2)) {
        playerX -= 5;
    else if(gamepadButtonPressedHandler(3)) {
        playerX += 5;
    if(gamepadButtonPressedHandler(11)) {
    // ...

That way we can control the player’s ship by pressing the corresponding DPad buttons, and even fire a bomb explosion with the A button. You could also detect the axes, or even build your own small library for handling gamepad input — check out the Desktop gamepad controls article for more details on that.

Unconventional controls

If you like, you can go even further and play a game with remote control on a huge TV screen standing in your living room, waving your hand in front of the laptop, or pressing everyday food connected with wires to your PC.


For example, Panasonic’s TV remote is surprisingly easy to implement controls with, as it reuses keyboard events, and the directional arrows have the exact same codes as keyboard cursor keys – 37, 38, 39 and 40, so it works out of the box. If you need more remote-specific buttons, here’s a full list, along with more detailed information.


Instead of pressing the buttons on a remote, you can use the ability of a Leap Motion device to detect your hand position and other parameters to take control of the player’s ship without touching anything. In a predefined loop we can get the hand details…

    hand: function(hand) {
        horizontalDegree = Math.round(hand.roll() * toDegrees);
        verticalDegree = Math.round(hand.pitch() * toDegrees);
        grabStrength = hand.grabStrength;

…and use them to update the player’s position:

function draw() {
    // ...
    if(horizontalDegree > degreeThreshold) {
        playerX -= 5;
    else if(horizontalDegree < -degreeThreshold) {
        playerX += 5;
    if(verticalDegree > degreeThreshold) {
        playerY += 5;
    else if(verticalDegree < -degreeThreshold) {
        playerY -= 5;
    if(grabStrength == 1) {
    // ...

You’ll find the implementation of other interesting control mechanisms like Doppler effect, Proximity API, or even MaKey MaKey in the Unconventional controls article.


These days, there’s a growing collection of devices large and small you can use to play HTML5 games. Your watch? A voice-activated web game? The possibilities are endless. And remember: the more control mechanisms your game can support, the better, because then it can be played on wide range of devices, on every possible platform. Take advantage of the opportunities enabled by the browser.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Web Font preloading for HTML5 games

In game development there are two methods of rendering text: via bitmap fonts and vector fonts. Bitmap fonts are essentially a sprite sheet image that contains all the characters of a given font. The sprite sheet uses a regular font file (traditionally .ttf). How does this apply to game development on the Web and HTML5 games?

You can use bitmap fonts as usual – they are just images, after all, and most HTML 5 game engines or libraries support them straight away. For vector font rendering, we can rely on any font that is accessible via CSS: this includes both system fonts already present in the player’s computer (like Arial or Times New Roman), or Web Fonts, which can be downloaded on the fly, if they are not already present in the system.

However, not all game engines or frameworks include mechanisms to load these fonts as regular assets –like images or audio files – and rely on them being present already. This can lead to quirks in which the game tries to render a text in a font that is not loaded yet… Instead, the player will get no text, or text rendered with an alternate or default font.

In this article we will explore some techniques for preloading Web Fonts into our games, and describe how to integrate them with a popular 2D game framework: Phaser.

How Web Font loading works

There are two ways of loading a Web Font: via CSS (using @font-face) or via JavaScript (using the Font Loading API). The CSS solution has been available for some time; while the JavaScript API is not widely adopted yet by browsers. If you want to release a game these days, we recommend the CSS method for its portability.

Declaration with @font-face

This is simply a declaration in your CSS code that allows you to set up a font family and point to the places where it can be fetched. In this snippet we declare a font family named Amatica SC, and assume that we have a TTF file as an asset.

@font-face {
  font-family: 'Amatica SC';
  font-style: normal;
  font-weight: 400;
  src: local('Amatica SC'),
       url(fonts/amaticasc-regular.ttf) format('truetype');

Note: In addition to pointing to specific files, we can also point to font names that might be installed in the user’s computer (in this case, Amatica SC or AmaticaSC-Regular).

Actual loading

It’s important to remember that declaring a font family via CSS does not load the font! The font is loaded only when the browser detects for the first time that it’s going to be used.

This can cause a visual glitch: either the text is rendered with a default font and then changes to the Web Font (this is known as FOUT or Flash Of Unstyled Text); or the text isn’t rendered at all and remains invisible until the font becomes available. In websites this is usually not a big deal, but in games (Canvas/WebGL) we don’t get the automatic browser re-rendering when the font is available! So if we try to render the text and the font is not available, it is a big deal.

So we need to actually download the font before we try to use it in our game…

How to force a Web Font download

The CSS Font Loading API

The JavaScript API does force a font to load. As of today, it only works on Firefox, Chrome, and Opera (you can check for the most up-to-date font-loading support information in

Note that when using FontFaceSet, you still need to declare your fonts somewhere –in this case, with @font-face in the CSS.

Typekit’s Web Font Loader

This is an open-source loader developed by TypeKit and Google – you can check out the Web Font Loader repository in Github. It can load self-hosted fonts, as well as fonts from popular repositories like Typekit, Google Fonts, etc.

In the following snippet we will load Amatica SC directly from Google Fonts and specify a callback function – to render text in a 2D canvas– that will be invoked when the fonts are loaded and ready for use:

FontFace Observer library

FontFace Observer is another open-source loader that doesn’t contain ad-hoc code for common font repositories. If you are self-hosting your fonts, this might be a better choice than Typekit’s since it is a lighter-weight file size.

This library uses a Promise interface – but don’t worry, there’s a version with a polyfill if you need to support older browsers. Here again, you need to declare your fonts via CSS as well, so the library knows where to go to fetch them:

Integrating font loading in Phaser

Now that we’ve seen how to load Web Fonts in HTML5, let’s discuss how to integrate these fonts with a game engine. The process will differ from one engine or framework to another. I have picked Phaser as an example, since it’s widely used for 2D game development. You can take a look at some online examples here:

And, of course, there is the Github repository with full source code, so you can take a closer look at what I’ve built.

Here’s how Phaser works: the game is divided in game states, each of which executes a sequence of phases. The most important phases are: init, preload, create, render, and update. The preload phase is where we must load game assets like images, sounds, etc. but unfortunately Phaser’s Loader does not provide a method for font preloading.

There are several ways to bypass or work around this issue:

Delaying font rendering

We can use the Font Loading API or a library to force a font download in the preload phase. However, this creates a problem. Phaser’s Loader doesn’t allow us to indicate it when all loading is completed. This means we can’t pause the Loader and prevent the preload phase from ending so that we can switch to create – this is where we would want to set up our game world.

A first approach would be to delay the text rendering until the font is loaded. After all, we have a callback available in the promise, right?

function preload() {
  // load other assets here
  // ...

  let font = new FontFaceObserver('Amatica SC');
  font.load().then(function () {
    game.add.text(0, 0, 'Lorem ipsum', {
      font: '12px Amatica SC',
      fill: '#fff'

There is a problem with this approach: What happens if the callback is invoked before the preload phase has ended? Our Phaser.Text object would then be wiped out once we switch to create.

What we can do is guard the creation of the text under two flags: one that indicates that the font has loaded, and a second one that indicates that the create phase has started:

var fontLoaded = false;
var gameCreated = false;

function createText() {
  if (!fontLoaded || !gameCreated) return;
  game.add.text(0, 0, 'Lorem ipsum', {
      font: '12px Amatica SC',
      fill: '#fff'

function preload() {
  let font = new FontFaceObserver('Amatica SC');
  font.load().then(function () {
    fontLoaded = true;

function create() {
  gameCreated = true;

The main disadvantage of this method is that we completely ignore Phaser’s Loader. Since this doesn’t queue the font as an asset, the game will start and the fonts will not be there — this will probably cause a blinking effect or a glitch. Another problem is that the “Loading” screen or bar will ignore fonts, will display as if 100% loaded, and switch to the game even though our font assets still haven’t loaded.

Using a custom loader

What if we could modify Phaser’s Loader and add it to whatever we need? We can! We can extend Phaser.Loader and add a method to the prototype that will queue an asset – a web font! The problem is that we need to modify one internal (meant for private use) Phaser.Loader method, loadFile, so we can tell the Loader how to load the font, and when loading has been finished.

// We create our own custom loader class extending Phaser.Loader.
// This new loader will support web fonts
function CustomLoader(game) {, game);

CustomLoader.prototype = Object.create(Phaser.Loader.prototype);
CustomLoader.prototype.constructor = CustomLoader;

// new method to load web fonts
// this follows the structure of all of the file assets loading methods
CustomLoader.prototype.webfont = function (key, fontName, overwrite) {
    if (typeof overwrite === 'undefined') { overwrite = false; }

    // here fontName will be stored in file's `url` property
    // after being added to the file list
    this.addToFileList('webfont', key, fontName);
    return this;

CustomLoader.prototype.loadFile = function (file) {, file);

    // we need to call asyncComplete once the file has loaded
    if (file.type === 'webfont') {
        var _this = this;
        // note: file.url contains font name
        var font = new FontFaceObserver(file.url);
        font.load(null, 10000).then(function () {
        }, function ()  {
            _this.asyncComplete(file, 'Error loading font ' + file.url);

Once this code is in place, we need to create an instance of it and swap it into game.load. This swapping must take place as soon as possible: in the init phase of the first game state executed.

function init() {
    // swap Phaser.Loader for our custom one
    game.load = new CustomLoader(game);

function preload() {
    // now we can load our font like a normal asset
    game.load.webfont('fancy', 'Amatica SC');

The advantage of this method is real integration with the loader, so if we have a loading bar it will not finish until the font has been completely downloaded (or timed out). The disadvantage, of course, is that we are overriding an internal method of Phaser, so we have no guarantee that our code will continue to work in future versions of the framework.

A silly workaround…

A method that I have been using in game jams is to not start the game at all until I know that the font is ready. Since most browsers won’t render a text until the web font has been loaded, I just create a splash screen with a Play button that uses the web font… This way I know that the button will be visible once that font has loaded, so it’s safe to start the game then.

The obvious disadvantage is that we are not starting to load assets until the player presses that button… But it does work and it is very simple to implement. Here’s an screenshot example of one of these splash screens, created with regular HTML5 DOM elements and CSS animations:

Screen Shot 2016-06-28 at 15.23.24

And there you have it, Web Font rendering in HTML5 games! In the future, once the Font Loading API is more mature, HTML5 game engines and frameworks will start to integrate it in their code, and hopefully we won’t have to do this ourselves or find a usable workaround.

Until then, happy coding! 🙂

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Basics of building 3D games on the Web

You might think that 3D games are harder to develop than 2D because of the extra dimension you have to take into account, but it’s easier than you think. We’ve recently updated the Games section on MDN with a collection of tutorials covering 3D development, with a focus on frameworks that offer shortcuts for developers who are getting started building games for the Web and are unfamiliar with WebGL.


WebVR and 3D game development

Virtual reality in the browser has made great progress this year, and the JavaScript API known as WebVR is under development. The WebVR specification is on the road to version 1.0. This will be a huge milestone for virtual reality technology in the browser. As the WebVR API matures, it will be time to move from “experimental” demos to the “production-ready” stage of serious commercial games and applications.

The A-Frame framework built on top of Three.js is rapidly evolving. There are case studies of interesting VR projects already like Cardboard Dungeon and SECVRITY. The framework itself has reached version 0.2.0 and is quickly gaining interest in the community. Its simple yet powerful approach uses markup to create VR experiences that works across platforms and devices. The result: New tutorials, demos, and plugins are being created every single day.


These are exciting times for cutting-edge VR experiments, but if you’re a fan of 2D games like me, jumping into the third dimension might be a challenge. Let’s explore the basics of 3D together, and see how some popular frameworks can help you achieve your goals more quickly, and create impressive games and demos.

The concept of 3D games on the Web is fundamentally about rendering WebGL on Canvas to create hardware-accelerated rich interactive animations. The basic theory revolves around the rendering pipeline, which manages the information about your creations, and displays them on the screen.


An overview of frameworks for 3D game development

You can do all that yourself in pure WebGL, or you can make your life easier, speed up development, and focus only on the important parts of your game idea with a variety of available frameworks. The MDN Games tutorials include:

Three.js is the most popular tool for WebGL animations, while PlayCanvas offers you a choice of using the PlayCanvas engine or the online editor to build a game or demo. Babylon.js is often picked for its simple API and powerful features. The A-Frame framework can also be used to build rapid prototypes of 3D worlds viewable immediately in virtual reality. We’ve also provided tutorials to cover fundamental concepts like shaders. Understanding what’s going on behind the scenes of the framework gives you greater control over how your game will look when all the post-processing is applied.

Advantages of frameworks

What are the advantages of using a framework for game development? Frameworks provide benefits and shortcuts. Here are some examples:


You can offload work that feels repetitive compared to other parts of creating a game: loading assets, rendering the scene, or drawing everything on screen. You won’t have to manage the specific configuration of cameras, lights, and such. Instead, you can create some geometry, add animation, and forget about everything else – it will just work and you’ll see your creation immediately.

You won’t have to worry about differences in how browsers implement features – that is taken care of by the framework and exposed for you in a simple, high level API.

Frameworks add an extra layer that abstracts many things, so you can write less code and do more with less. A framework can help you focus on the core mechanics of your game. Sometimes a few lines of framework-specific code do exactly the same as dozens of lines of pure JavaScript implementation. (Keep in mind this isn’t always the case.)


Different frameworks offer different experiences: Three.js is generally used to create animations; Babylon.js, on the other hand, is focused on creating games. It can also take care of anti-aliasing for you. Both frameworks can be used successfully to create games, so the choice really depends on your preferences and project goals.

Some frameworks even add an extra layer of features and offer built-in physics engines, collision detection, or particle systems. All of that infrastructure is available to use in your project without the compatibility issues you’d need to address to use custom plugins or write these functionalities from scratch.

It’s easier to start and quickly prototype a scene using frameworks – they offer low level of complexity to build complex creations. See how the source code of a simple 2D Breakout game in pure JavaScript is longer and more complicated than the same game in Phaser. Using a framework saves you time, so that you can focus on actually building something unique.


In conclusion

On the other hand, it is good to learn the language first to know how frameworks are built, why this way and not the other, and to be able to extend them if they are not doing exactly what you want them to. Frameworks tend to go in and out of fashion, and it can be an extra effort to learn their syntax. After all, you can always write a simple feature yourself in pure JavaScript – that’s a powerful skill.

Check out my GitHub repository for a collection of demos showcasing how to build a simple 3D scene with the given tools or view them online.

Remember: you don’t have to use any specific framework, and can achieve comparable results in pure JavaScript with WebGL. The demos shown above were picked to illustrate how to use the most popular tools right now. If you think I’m missing something, you can write about it and add it to the Github collection of 3D demos above – all contributions are welcome. If I did not include your favourite framework you can suggest it in the comments below or write an intro yourself, so more people know about it.

Feel free to use the source code however you like — for example as a boilerplate for your new 3D project — and remember to show us what you’ve built on top of this! We’d love to hear from you right here in comments or over on the Github repo.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Building games for Firefox OS TV

With Firefox OS focused on a world of connected devices, it’s a good time to start building games for new and different displays. Panasonic offers a variety of Firefox OS-powered TVs — in this article we’ll outline how developing HTML5 games for huge television screens differs from the smartphone approach.

Captain Rogers revisited

My gamedev journey as Enclave Games founder and developer started with the first version of Captain Rogers (called Asteroid Belt of Sirius) — it was built almost three years ago for low-end smartphones and optimized for small screens. I remember seeing it running smoothly on the Geeksphone Keon, a device with a 3.5″ screen; back then I couldn’t have imagined I would be working on the same game for a 50″ TV.


I was always interested in building HTML5 games using brand new technologies, implementing cutting-edge APIs, and developing for new platforms, that’s why I was so excited when I tested my game on the Keon device and realized it was working smoothly. When I saw the first smart TVs appearing on the market I wondered if one day we’d have one of those running Firefox OS, and how the performance and ease of development would compare to smartphones and the PC-based web. The premiere of the new Panasonic TVs is a great excuse to dust off the old Captain Rogers and see if he still has the spark to impress the audience, even though the audience itself has changed over these last few years.

Planning the new version

I decided to rebuild Captain Rogers with current technologies and for bigger screens (with TV in mind). The original game was created using the ImpactJS game engine with a low base resolution of 480 x 320. Moving towards the present day, I’ve now been working with Phaser to make games for more than two years, and I think it’s currently the best game engine out there for casual 2D games.

The performance of browser rendering engines has gotten a lot better, so it I didn’t think it would be a problem to make the game bigger and still keep the high frame rate. That’s why I decided to give the new version of Captain Rogers a base resolution of 960 x 640 pixels — more than enough to make the game look a lot better than the original.


At first I wanted to create an exact copy of the original game logic using the new framework. Originally it was going to be a direct HD remake, but I then decided to add extra features like shooting, floating enemies, and extra some visual effects. You can therefore consider it a second episode. You can already play the demo that is being showcased now on Panasonic TVs running Firefox OS at CES 2016 in Las Vegas.

I’m currently working with Blackmoon Design on the full version of Captain Rogers 2: Battle at Andromeda, that will be released in the next month or two.

Starting development

Many resources have been written over the years on how to prepare your HTML5 game for Firefox OS smartphones. With the new medium, the approach is not much different (with some exceptions that are discussed below), so you can largely follow that. To start developing games for Panasonic TVs with Firefox OS you’ll need Firefox Nightly and WebIDE — all the step-by-step instructions on how to push the game to a TV through WebIDE’s remote debugging can be found in this MDN article.

Considering huge screens

The TV in your living room is obviously different than the smartphone you’re holding in your hand, and games and other applications have to be designed somewhat differently for the new medium. And yet, building for the Web has taught us that a game should adjust its size to the screen no matter if it’s a smartphone, tablet, laptop or PC monitor, so a TV screen shouldn’t be much of a problem, and it isn’t.


Scaling in Phaser can be a one-liner:

this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;

This will take care of scaling the game’s Canvas to the available screen space and maintaining the aspect ratio, so it won’t be stretched in any way. There are other ways to scale a game, but this one is the simplest, most universal solution. It will work for small smartphones and huge TVs — the only thing to consider is the resolution of the assets versus the performance of the game, so it looks good and performs reasonably well at the same time. Decisions about resolution depend on the type of game you’re building, how many assets there will be, or how much is going to happen on the screen, so it’s an individual choice.


It’s good to know that the remote control can emulate keyboard keys, so if you have already implemented that for your game it will work out of the box:

this.cursors = this.input.keyboard.createCursorKeys();
if(this.cursors.right.isDown) {
    this.player.body.velocity.x += forcePush;

In this case, the cursor keys (corresponding arrows on the keyboard if you’re testing and playing the game on desktop) are created and can be checked later on. They have the same key codes as the arrows on the remote, that’s why it’s easier to implement and test them. If the right arrow key is pressed when playing the game, then the player’s ship will move right. You can find the exact same keys on the remote control:


The four directional arrow keys have the exact same key codes as their keyboard counterparts, but how do you check the other keys on the remote? You can do it with a pure JavaScript approach:

window.addEventListener("keydown", function(evt) {
}, this);

This way you’ll see the related key codes being printed in the console when pressing the buttons on your remote, so you can assign actions to them correctly in the game. You can also check the TV remote control button mapping to keyboard article to make your life easier.


It’s important to know that TVs and other such devices tend to have hardware limitations. To make the game work smoothly it’s important to follow a few guidelines and test performance to remove any potential bottlenecks. See this Power Surge article for tips.

Going open source

When preparing the demo of the new Captain Rogers I decided to complete and open source my private template that I, as Enclave Games, use for game development — you can find the Enclave Phaser Template on GitHub. I also realized that I already have a few gamedev projects there (like Monster Wants Candy and Cyber Orb), and it would be cool to list all of them on one page so developers can learn and benefit from them: I therefore also published, a list of my most interesting open source projects.

From MWC to CES

I was demoing the first Captain Rogers at Mobile World Congress 2014 in Barcelona on a range of Firefox OS smartphones. Since then, I’ve done a lot of talks about building games for Firefox OS with Captain Rogers included as a case study. Now it is time for the new game to be shown on Firefox OS television at the Consumer Electronics Show in Las Vegas, where new Panasonic UHD TVs have been unveiled. If you’re going to attend be sure to visit Mozilla at the Panasonic booth and check the game out. Give it a try and see if game development on TVs is something you’d like to do in the future. If it is, then feel free to ping me on Twitter and ask questions — I’m more than happy to help out.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

HTML5 games: 3D collision detection

Last week we took a look at Tilemaps, and I shared some new articles that I’d written on MDN. This week I’m back to introduce 3D collision detection, an essential technique for almost any kind of 3D game. I’ll also point you to some more new articles about game development on MDN! Hope they inspire you to stretch your skills.

In 3D game development, bounding volumes provide one of the most widely used techniques for determining whether two virtual objects will collide (i.e., intersect with each other) during game play. The technique of bounding volumes consists of wrapping game objects with some virtual volumes, and applying intersection algorithms to describe the movement and interaction of these volumes. You can think of this approach as a shortcut: it is easier and faster than detecting intersections between arbitrary, complex shapes.

In terms of bounding volumes, the use of axis-aligned bounding boxes (AABB) is a popular option. Depending on the game, sometimes spheres are used as well. Here’s an image of some 3D objects wrapped with AABB:

Screen Shot 2015-10-16 at 15.11.21

The new MDN article on 3D collision detection describes how to use generic algorithms to perform 3D collision detection with AABB and spheres. This article should be useful regardless of the game engine or programming language you are using to develop your game.

We also published an article about doing collision detection with bounding volumes using three.js, a popular 3D library for JavaScript. (Learn more about three.js.)

Check out the live demos and peek at their source code. One of the demos uses a physics engine (in this case, Cannon.js) to perform collision detection. Embedded below you can find another demo that shows how to use Three.js to detect collisions:

Hope you enjoy the demos and find them useful. If there’s a particular topic in HTML5 game development you’d like to learn more about, please drop a comment here and let us know! We’ll try to get it covered for you.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

HTML 5 games: Tilemaps

I recently joined the Developer Relations team at Mozilla, and my current focus is to help to create content for MDN about HTML 5 game development. I’m very excited about this, since creating games is a passion of mine. I switched to HTML5 game development to increase the reach of my games – which, by the way, is also a great thing to do if you are participating in a game jam.

Part of what we have been working on is a set of MDN articles about 2D tilemaps, a popular technique in game development – both in classic games and also recent ones.

Take this screenshot, for instance:

Mockup of a tile-based game - by Kenney

Game mockup out of an open-source tileset by Kenney

See how the game level is made up of smaller, square images? These smaller pieces are called tiles. A lot of games are based on tiles, visually and/or logically: Super Mario Bros, SimCity, Final Fantasy Tactics, Civilization, etc.

The “Tiles and Tilemaps overview” article provides a foundation about how tilemaps work. You will find it useful regardless of how you use them in your game (your own implementation or a 3rd-party) –or even the programming language or technology!

We have also written articles about how to implement tilemaps using the Canvas API:

Accompanying those articles there is a set of live demos you can check out, along with their source code. But there is one for you to try right here: click on the image below and then use the arrow keys to move the character.

We will keep working on creating new MDN content for HTML5 game development and keep you updated. I hope you enjoy it!

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Programming games in the browser

A programming game is a computer game where two or more programs compete with each other. What are the basic requirements for programming games and can they be realized in browsers? With JavaScript?

4 basic claims

There are 4 basic claims. Competing programs:

  • must run isolated from the main program.
  • must communicate with the main program in a defined way.
  • should run parallel. Parallel to the main program and parallel to each other.
  • should be injected in the playing environment in an easy way.

The good old JavaScript is running synchronously and there is no way to isolate subprograms. But times are changing and modern JavaScript has a lot more features. What about Web Workers? They were designed to make JavaScript faster, running expensive calculations in the browser without blocking the user interface. But Web Workers can do more. They meet our claims about programming games! They run isolated from the main program, communicate with the main programs by events, run parallel and thanks to the new File API they can be injected locally.


That’s all. It’s really easy creating programming games with Web Workers. To show this idea working in May 2014 I launched a simple programming game based on Web Workers, the WEB WORKER CONTEST. The actual game is a simple mathematical challenge: How to conquer a square of 100×100 fields. Starting from a random point the player must conquer a playing area of 100×100 fields with simple moves (up, down, right, left).

A new field can be occupied only if it was not previously occupied by the opponent’s program. The players do not have any information about the playing area. The only information they receive is whether their chosen move is possible or not. So, the Web Worker use postMessage() to send their new move. And with the onmessage() event they receive whether their move was possible or not (a simple true or false). The main program do it vice versa. It receives the move with onmessage(), execute the move on the playing area and send the success with postMessage().

In the end your code looks like this:

// - worker1.js -
// makeMove() calulates the next move
onmessage = function (event) {
  var success =;
  var direction = makeMove(success);
    direction: direction
// - main program -
// makeMoveWorker1() executes the move
var worker1 = new Worker('worker1.js');
worker1.onmessage = function(event) {
  var direction =;
  var success = makeMoveWorker1(direction);
    success: success

Now, just start the game with

// analogously for a second worker
  success: true

and it’s in full swing.

The complete code is available on GitHub.

The main challenge: equal distribution of machine time

The main challenge for programming games with Web Workers is the equal distribution of machine time to both Web Workers. There are 2 separate time problems. One in the loading phase, the other in the playing phase.

Before starting the game, both Web Workers must be loaded (remote or local). So, before starting the game you must wait until both Web Workers are loaded. Unfortunately there is no onload event for Web Workers. Of course we can do something about this: In the beginning the main program sends an ‘are-you-ready’ post to the player and starts the game after both workers confirm this post.

The equal machine time during the playing phase is in general not under the control of the main program. It can happen that one player can do lots of moves before the other player can move. To get equal conditions for both players is a challenge for both the browser engine and the operating system. But it is possible that one player try to block the other by permanent firing (with a postMessage loop). To prevent this the main program send, together with the success information, a random ID. The player must resend this ID with his next move (otherwise he will be disqualified). With this restriction the machine time is sufficiently equally distributed.

More videos are available on YouTube.

The contest and programming games

The WEB WORKER CONTEST was very agile. During 4 weeks over 200 programmers with over 700 programs tinkered on the best strategy to conquer the field.

Programming games in the browser works. With the Web Worker technology we have the instrument to realize them. And programming games in the browser are very handy for the participants. No need for installing a playing environment. Just go to the web site, write your code, test and upload it.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

asm.js performance improvements in the latest version of Firefox make games fly!

The latest version of Firefox which launched last week includes a major update to the user interface as well as to features like Sync. Another area in which this release brings significant improvements is in asm.js performance, which as we will see below is very important for things like games. To put that aspect of Firefox’s performance in context, we’ll take a look at benchmark results comparing Firefox to other browsers, which show that Firefox is faster at executing asm.js code.

asm.js speedups

asm.js is a subset of JavaScript that is very easy to optimize and is particularly useful for porting code in C or C++ to the Web. We’ve blogged about how Firefox can optimize asm.js code using 32-bit floating point operations, which, together with all the other work on optimizing asm.js, allows it to run at around 1.5x slower than the speed of the same C/C++ when compiled natively. So, while not quite native speed yet, things are getting very close. At the time of that blog post those optimizations were only on nightly builds, but they are now reaching hundreds of millions of Firefox users in Firefox 29, which is now the release version of Firefox.

Another important set of asm.js optimizations concern startup speed. As blogged about by Luke a few months ago, Firefox performs ahead of time (AOT) compilation and can cache the results, for significant speedups in startup times. Those optimizations also shipped to users in Firefox 29.

Web browser comparisons

Now that all those optimizations have shipped, it’s interesting to look at up-to-date browser comparisons on asm.js code. The above graph shows the Emscripten benchmark suite running the latest stable versions of Google Chrome, Internet Explorer and Firefox on Windows 8.1. Lower numbers are better in all the results here, which are real-world codebases compiled to asm.js (see notes in the graph).

Unity, Emscripten and asm.js

asm.js is a subset of JavaScript, so it is just one of many styles of JavaScript out there. But it represents an important use case. As we announced at GDC, Unity, one of the most popular game creation tools on the market, will support the Web by using Emscripten to compile their engine to asm.js.

But videos are no substitute for the real thing! You can try the games shown there in your browser right now, for instance with Unity’s recently released Angry Bots demo. If you run those in the latest version of Firefox, you’ll see many of the asm.js optimizations mentioned earlier in action. For example, if you visit one of those links more than once then asm.js caching will allow it to avoid recompiling the game (so it starts up faster), and also gameplay will be smoother due to faster asm.js execution.

Being able to execute asm.js-style code efficiently makes it possible for games like this to run well on the Web, without proprietary, nonstandard plugins. That’s why it’s exciting to see more asm.js optimizations reach Firefox users in Firefox 29. And while benchmark results can sometimes seem like nothing more than abstract numbers, speedups on asm.js benchmarks directly improve things like games, where performance is extremely important and very noticeable.

(Thanks to Marc Schifer for helping with the benchmark measurements.)

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Monster Madness – creating games on the web with Emscripten

When our engineering teams at Trendy Entertainment & Nom Nom Games decided on the strategy of developing one of our new Unreal Engine 3 games — Monster Madness Online — as a cross-platform title, we knew that a frictionless multiplayer web browser version would be central to this experience. The big question, however, was determining what essential technologies to utilize in order to bring our game onto the web. As a C++ oriented developer, we determined quickly that rewriting the game engine from the ground-up was out of the question. We’d need a solution that would allow us to port our existing code in an efficient manner into a format usable in the browser…

TL;DR? Watch the video!

Playing the Field

We looked hard at the various options in front of us: FlasCC (a GCC Flash compiler), Google’s NaCl, a custom native C++ extension, or Mozilla’s Emscripten & asm.js.

In our tests, Flash ran slowly and had inconsistent behaviors between Pepper (Chrome) and Adobe’s plugin version. Combined with the increasingly onerous plugin requirement, we opted to look elsewhere for a more seamless, forward-thinking approach.

NaCl had the issue of requiring a walled-garden distribution site that would separate us from direct contact with our users, and also being processor-specific. pNaCL eliminated the walled-garden requirement and added dynamic code compilation support, but still had the issues of being processor-specific code necessitating in our view device-specific testing, and a potentially long startup time as the code would be linked on first run. Finally, only working in Chrome would be a dealbreaker for our desire to have our game run in all major browsers.

A custom plugin/extension with C++ would require lots of testing & maintenance efforts on our part to run across different browsers, processor architectures, and operating systems, and such an installation requirement would likely scare away many potential players.

As it turned out, for our team’s purposes the Emscripten compiler & asm.js proved to be the best solution to these challenges, and when combined with a set of other new-ish Web API’s, enabled the browser to become a fully featured platform for instant high-end 3D gaming. This just took a little trial & error to figure out exactly how we’d piece it together…and that’s what we’ll be reviewing here!

First Steps into a Brave New World

We Trendy game engineers are primarily old-school C++ programmers, so it was something of a revelation that Emscripten could compile our existing application (built on Epic Game’s Unreal Engine 3) into asm.js optimized Javascript with little to no changes.

The primary Unreal Engine 3-specific code tweaks that were necessary to get the project to compile & run with Emscripten, were essentially… 1, 2, 3:

// Esmcripten needs 4 byte alignment
FNameEntry* Allocate( INT Size )
       Size = Align( Size, 4 );
// Script execution: llvm needs aligned data
    #define XFER(T)
        T Temp;
        if (!Ar.IsLoading())
            appMemcpy(&Temp, &Script(iCode), sizeof(T));
        Ar << Temp;
        if (!Ar.IsSaving())
            appMemcpy(&Script(iCode), &Temp, sizeof(T));
        iCode += sizeof(T);
    #define XFER(T) { Ar << *(T*)&Script(iCode); iCode += sizeof(T); }
// This function needs to synchronously complete IO requests for single-threaded Emscripten IO to work, so added a ServiceRequestsSynchronously() to the end of it which flushes & blocks till the IO request finishes.

No really, that was about it! Within a day of fiddling with it, we had our game’s Javascript ‘executable’ compiled & running in the browser. Crashing, due to not having a graphics API implememented — but running with log output! Thankfully, we already had Unreal Engine3’s OpenGL ES2 version of the rendering subsystem ready to utilize, so porting the renderer to WebGL only took another day.

WebGL appeared to essentially have a superset of features compared to OpenGL ES2, so the shaders and methods used matched up by simply changing some API calls. In fact, we were able to do improvements by making use of WebGL’s floating point render targets for certain postprocessing effects, such as edge outlining and dynamic shadows.

Postprocessing makes everything prettier!

But how’s it run?

Now we had something rendering in the browser, and with a quick change to capture input, we could start playing the game and analyzing its performance. What we found was very encouraging: straight ‘out of the box’, in Firefox the asm.js version of the game was getting nearly 33% of the performance of the native executable. And this was comparing a single-threaded web application to the multi-threaded native executable (so really, not a fair comparison! ;). This was about 2x the performance we saw with our quick Flash port (which we still utilize as a fallback for older browsers that don’t yet support asm.js, though we eventually hope to deprecate entirely).

Its performance in Chrome was less astonishing, more towards 20% of native performance, but still within our target margins: namely, can it run on my mom’s 2011-model Macbook Air at 45-60 FPS (with Vsync disabled)? The answer, thankfully, was yes. We hope Google will continue to improve the performance of asm.js on their browser over time. But as it currently stands, we believe unless you’re making the browser version of ‘Crysis’ with this tech (which may not be far off), it seems you have enough performance even in Chrome to do most kinds of web games.

60 FPS on an old Macbook Air, our “Mom’s Computer” Test

Putting the Pieces into Place

So within a week from starting, we had turned our Unreal Engine 3 PC game into a well-running, graphically-rich web game. But where to take it from here? Well, it’d still need: Audio, Networking, Streaming, and Storage. Let’s discuss the various techniques used for each of these systems.


This was a no-brainer, as there is only really one robust standardized web audio system apart from Flash: WebAudio. Again, this API matched up pretty well to its mobile cousin, OpenSL, for which we already had an integration. So once we switched out the various calls, we had .

There was an apparent issue in Mac Chrome where sounds flagged “looping” would sometimes never become destroyed, so we implemented a Chrome-specific hack to manually loop the sound, and filed a bug report with Google. Ah well, one thing we’ve seen with browser API’s is there’s not a 100% guarantee that every browser will implement the functionality to perfect specification, but it gets the job done!


This proved a little trickier. First, we investigated WebRTC as used in the Bananabread demo, but WebRTC of course is for browser-to-browser communication which is actually not what we were looking to do. Our online game service uses a server-and-client architecture with centralized infrastructure, and so WebSockets is the API to utilize in that case. The tricky part is that we have to handle all the WebSockets incoming and outgoing data in JavaScript buffers, and then pass that along to the “C++” Emscripten-compiled game.

With some callbacks, this worked out, but we also had to take our UDP game server code and place the WebSockets TCP-style layer onto it — some iteration was necessary to get the packets to be formatted in exactly the way that WebSockets expects, but once we did that, our browser game was communicating with our backend-hosted Linux dedicated game servers with no problems!

Streaming & Storage

One advantage to being on the web is easy access to the browser’s asynchronous downloading functionalities to stream-in content. We certainly made use of this with our game, with the initial download clocking in at under 10 MB. Everything else streams in on-demand as you play using standard browser http download requests: Textures, Sound Effects, Music, even Skeletal Meshes and Level Packages. But the bigger question is how to reliably store this content. We don’t want to just rely on the browser cache, since it’s not good for guaranteed immediate gameplay loading as we can’t pre-query whether something exists on disk in the regular browser cache or not.

For this, we used the IndexedDB API, which lets us asynchronously save and retrieve data objects from a secure abstracted storage location. It works in both Chrome and Firefox, though it’s still finicky as the database can occasionally become corrupted (perhaps if terminated during async writes) and has to be regenerated. In the worst case, this simply results in a re-download of content the user already had received.

We’re currently looking into this issue, but that aside, IndexedDB certainly works well and has the advantage of providing our application standard file IO functionality, useful to store content that we download. (UPDATE: Firefox Nightly build as of 12/10 seems to automatically reset the IndexedDB storage if this happens and it may not recur.)

Play it Now, and Embrace the Future!

While we still have more profiling and tweaking to, as we’re just now starting to use Firefox’s VTune support to symbolically profile the asm.js performance within the browser. Even still, we’re pretty pleased with where the things currently stand. But don’t take our word for it, please try it yourselves right here, no installation or sign-up required:

Try our demo test anonymously In-browser Here!
(Please bear with us if our game servers limit access under load, we’re still testing our backend scalability!)

We at Trendy envision a day when anybody can play any game no matter where they are or what device they happen to have, without friction or gateways or middlemen. With the right combination of these cutting-edge web technologies, that day can be today. We hope other enterprising game developers will join us in reaching players directly through the web, which thanks to Emscripten & asm.js, may well become the most powerful and far-reaching “game console” of all!

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)