Game

js13kGames: Code golf for game devs

How much is 13 kB? These days a couple of kilobytes seem like a drop in the ocean. Rewind back to the dawn of video game history, however, and you’ll soon realise that early pioneers had to work with crazy limitations.

The beloved Atari 2600, for example, had a measly 128 bytes of RAM with cartridges supplying an additional 4 kilobytes. As the saying goes: constraints inspire creativity. The annual js13kGames competition channels creativity by challenging aspiring game developers to create a game using just 13,312 bytes, zipped.

A coding competition for HTML5 game developers

Js13kGames is an annual online JavaScript competition for HTML5 game developers that began in 2012. The fun part is the file-size limit, set to 13 kilobytes. Participants have a whole month (August 13th – September 13th) to build a game on the given theme – in 2015, the theme was Reversed.

js13kgames banner

Thanks to our friends and sponsors, this competition offers plenty of prizes, includes a panel of expert judges, free t-shirts, and other goodies, shipped worldwide for free. But winning is only one of the benefits of participation. There’s lots to be gained from being a part of the js13kGames community. People help each other if they’re stuck on something, share their tools, workflows, tips, and tricks. Plus, the constraint of a limited time frame helps you finish a game, and trains your skills in the process.

Last year’s winners

Thirteen kilobytes is not enough even for a low resolution image. The small screenshots on the entries pages are usually bigger than the games themselves! And yet, you may be surprised by what can be achieved in such a small size. Take a look at some of last year’s winners for inspiration:

Wondering how such features are implemented? I’ve interviewed the winners, asking them to share some of their secrets to success. They share tooling and techniques for game development with extreme constraints. And if you’re craving more details: all games are on GitHub, so you can dig through the source code yourself.

RoboFlip

RoboFlip

Eoin McGrath describes some aspects of his workflow for RoboFlip:

“The final entries can be zipped. Zip compression works much better on a single file than multiple files, so the best thing to do is inline all images, concatenate files, minify your JavaScript and remove any white space. Thanks to task runners like Grunt and Gulp this process can be largely automated. Check out the Gulp file that I used. A simple gulp build command takes care of all the heavy lifting and lets me know how much valuable space I have left.”

Gulp build task in action

Graphics

“First off, forget about high resolution sprite sheets with lots of animation frames. Simplicity is the key. A lot can be achieved with procedural generation or SVGs. I personally went for a retro-style pixellated look. First, all images were created at tiny resolutions (from about 6×6 pixels) in GIMP. I then encoded them in base64 and used the Canvas API to redraw them at a larger scale.”

Scaled up sprites

“Another handy trick I used was to run all images through a function that replaced non-transparent color values with white.”

Damage frame for crate sprite

“This proved a cheap and effective way to have damage frames available for all sprites.”

Sound

“A game with no sound effects is like coffee without the caffeine. Obviously, there is no way you can fit a single .mp3 or .ogg file into your game with the given limitations. Thankfully, there is jsfxr, which is a very nice library you can use to create some 8bit styled beeps.

For the musically inclined you can also have a stab at creating a soundtrack
using the Sonant-X library – check out this awesome playable example.”
(You may need to hit “Play Song” to initiate.)

Road Blocks

“One of the things I love about the js13kGames competition is the artificial limitation it places on you in terms of what you can achieve,” writes Ash Kyd, a game developer from Australia.

“I find as an indie dev, with more open-ended projects it’s possible to get bogged down by all the possibilities and end up with nothing to show at the end, whereas setting some hard limits makes you more creative in terms of what you can accomplish.”

Road Blocks

“Thanks to the filesize limitation, Road Blocks is a fundamentally simple game and didn’t require a massive amount of coding work. As a result, a lot of my time was spent polishing the gameplay and smoothing rough edges during the competition, which resulted in a higher quality product at the end of the month.”

Behind Asteroids – The Dark Side

“Js13kGames is a great opportunity to discover and experiment with cool technologies like WebGL or Web Audio — and improve your skills. With a 13 kB limit, you can’t afford to hide behind a framework. Also, obviously, you shouldn’t use images but try to procedurally generate them. That said, it’s up to you to find your style and use the tricks that suit you. Don’t fall into doing all the tricks right away – prototype first and compress your code at the very end,” advises veteran game developer and js13kGames winner Gaëtan Renaudeau.

Behind Asteroids

“One of the interesting tricks I’ve found to save bytes is to avoid object-oriented style. Instead, I just write functions and use Arrays as tuple data type – I’ve used this technique in the past for a previous js1k entry.

This is the third year I’ve participated in the js13kGames competition and the third time I’ve had fun with WebGL. My 2015 submission is a remake of Asteroids where you don’t actually control the spaceship but you instead send the asteroids. This is my take on the Reversed theme.

On desktop, the game is implemented by typing – a letter is displayed on each asteroid and you have to type it at the right moment. On mobile, it simply turns into a touch-enabled game.

The game is paced with different levels from beginners to more experienced players who control the spaceship which you must destroy with the asteroids. The spaceship controls are driven by an AI algorithm.”

How the game is rendered

“The game uses hybrid rendering techniques: it is first rendered on Canvas using basic 2D shapes and is then piped into multiple WebGL post-processing effects.

The 2D Canvas drawing involves circles for particles and bullets, polygons for asteroids and spaceships, and lines for the procedural font as the path of each letter is hardcoded. Game shapes are drawn exclusively with one of the 3 color channels (red, blue and green) to split objects into different groups that the post-processing can filter – for instance, bullets are drawn in blue so we can apply specific glare effects for them. This is an interesting technique to optimize and store different things into a single texture as the game is in monochrome.

The different effects involved in the WebGL post-processing are detailed in this post-mortem. The important goal of this final step is to graphically reproduce the great vector graphics of the original arcade machine.

A background environment map where you see a player reflecting into the arcade game screen is also added in the background. It is entirely procedurally generated in a Fragment Shader.”

Summary

You can employ a myriad of approaches to shave precious bytes off your code base. These range from the fairly well known to the more obscure. There’s an article on How to minify your HTML5 game over at Tuts+ Game Development, and you will also find a nicely curated list of tools and other materials at js13kGames Resources page.

I hope you’ve enjoyed this brief tour of js13kGames landscape and some of the winning code golf tricks past winners recommend. Tempted to give it a go this year? The 2016 competition starts in just a few days – on August 13th. Join us! It’s not too late to start 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)

Exporting An Indie Unity Game to WebVR

WebVR holds the key to the future of VR content access – instant gratification without any downloads or installs. Or, at least we think so! We’re building a multi-platform digital game subscription service called Boondogl that delivers native web games to desktop, mobile, console, and VR devices, and we’ve bet our entire business on native web technologies – HTML5, WebGL, JS, and soon WebAssembly. We set out to demonstrate how powerful the web will be for virtual reality, by building an Oculus Rift WebVR game for Boondogl. We built SECVRITY in a month. With such a short window, we didn’t have time to dive into the WebVR API to build it natively on the web. So, we built the game in our engine of choice – Unity 5.

SECVRITY is probably best described as “Whac-A-Mole for viruses”. You play as a computer security specialist trying to thwart a barrage of incoming viruses on your panoramic monitor setup. To disable viruses, you have to – you guessed it – look at the screen currently being attacked and click on it. While the potential for whiplash is fairly high, the potential for fun ended up being even higher, as evidenced by the barrage of people playing it in Mozilla’s Booth at GDC!

SECVRITY at GDC

Back to the technology though – Unity supports both WebGL and VR, but we quickly discovered that they were mutually exclusive and Unity did not have WebVR on their immediate roadmap. We started searching for ways to bridge this gap. Since Unity’s WebGL export spit the game out in website form, there had to be a way to connect the WebVR API to our Unity game to pipe the WebVR input into the engine. We were really hoping to not have to try and write it in that one-month window.

Luckily, one brave soul who goes by gtk2k on GitHub decided to build this bridge for everyone, almost a full year ago. His method is straightforward: he built a Unity WebGL template which includes JS files to handle WebVR input via the API, then he piped that code into Unity through one simple script. To implement the script properly in Unity, he created a camera prefab that houses 3 different cameras – a standard view camera, which is a normal Unity camera; and two stereo cameras that display side-by-side with slightly adjusted x-positions and viewport rects. The developer simply has to replace the main camera in their scene with this prefab, attach StereoCamera.cs to it, and watch the magic work. gtk2k’s bridge very cleverly makes the switch from standard camera to stereo cameras when the user hits the “Enter VR” button in the customized WebVR Unity template.

oculus-rift-vr-headset-1200x698

Download a Sample Unity WebVR Project or grab the UnityPackage to import the necessary files into your own project.

To try out the template yourself, here’s what you’ll need to do:

  • Get your hands on an Oculus Rift. Ensure that you enable running apps from external sources.
  • Download and install Firefox Nightly.
  • Install the WebVR enabler.
  • Grab either the entire sample project or just the UnityPackage above.
  • Open Unity (either the sample project or your own project with the UnityPackage added) and replace your MainCamera with the WebVRCameraSet prefab. tut1
  • Make sure StereoCamera.cs is attached to the parent node of the prefab. tut2
  • From File > Build Settings, select WebGL as the platform (but leave Development Build unchecked). tut3
  • Open Edit > Project Settings > Player to access the Player settings; under Resolution and Presentation, select WebVR as your WebGL Template. tut4
  • In the same project settings, under the Publishing Settings section, ensure your WebGL Memory Size is set to a minimum of 512 MB to avoid out-of-memory errors. (For SECVRITY, we set it to 768 MB.) tut5
  • Build to WebGL, and give it a shot in Firefox Nightly!
    • You can test local builds or upload the build to your favorite web host.

Hopefully that will get you up and running with your first Unity WebVR build! To test in the editor, you’ll need to enable the standard features for desktop VR builds. Go back to Edit > Project Settings > Player, select the Standalone tab (indicated by down arrow icon) above the Resolution and Presentation section, navigate to Other Settings, and check the boxes for both Stereoscopic Rendering and Virtual Reality Supported. These aren’t necessary for the WebVR build itself, but you’ll need them to test in the editor.

tut6

To supplement the template from a design perspective, we added explicit instructions to properly get the user into VR mode in their browser window. We also decided to give the user a choice whether to play in VR or with a mouse. This is where things got tricky.

mainmenu

We wanted non-VR users on desktop to be able to play SECVRITY since, well, it’s in a browser! We supported mouse controls before we supported VR, so mouse control in itself was simple. However, mouse control while VR input was being detected caused some incredibly wonky results. Essentially, the mouse movement would throw off the viewport of the VR headset, causing the user to: A. get completely lost, and B. get super sick. We had to detect whether or not the user was in VR and then disable mouse control to solve this.

Our solution is to completely disable mouse control, whether the player is using VR input or not, until they explicitly select “mouse” control from the main menu. The user must now select their input method of choice via arrow keys or controller joystick before playing. If the user chooses “mouse” while in a VR headset, then the sickness-inducing issues begin. Caveat player: we built this game in one month! Auto-detection will resolve this in future iterations.

SECVRITY_mainmenu

We learned some valuable lessons in building for WebVR via Unity, mainly in designing for hybrid VR/non-VR experiences. A lot of our troubles should be solved in an official WebVR export from the engine. But even when that comes, it’s still important to understand what your user may or may not do to break your game, especially when the control inputs are so drastically different. We had to make a few tweaks to gtk2k’s code for the enter VR flows to work with recent changes to Firefox Nightly, but his codebase largely worked as advertised with very little effort on our end. That man is our hero.

The web is the future of gaming, and Boondogl, armed with games like SECVRITY, will prove it to the world. Web gaming provides almost instant access to games on desktop, mobile, console, VR headsets, and other devices, with no permanent downloads or installs required for users. The web can already deliver near-native speeds and, with WebGL 2.0 and WebAssembly on the horizon, we’ll start seeing near-current-generation graphics as well. Boondogl hopes to help drive the web revolution forward and make the web the ultimate home for games on all devices. If you want to follow Boondogl’s progress, you can sign up for our newsletter and for a beta key at boondogl.com. And if you want to play SECVRITY right now, you can find it at as a demo on mozvr.com! Take it from us: the web will revolutionize the gaming industry. And WebVR will play an important role in showcasing the web’s power to both developers and users by providing instant access to beautiful virtual reality right from a 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)

HTML 5 game development video series

Do you want to develop a game? Here’s an introductory video series to get you started on HTML 5 game development!

Why HTML 5

The first video offers some reasons to consider making a game for the web: the power of having no friction in distribution, the freedom from siloed marketplaces, the choice of tools and APIs that are available to you, etc.

Engines and libraries

The second video provides an overview of the current engines and libraries you can use to create your game. We cover pure JavaScript libraries (such as Phaser) as well as multi-platform engines that can export to HTML 5 (such as Unity).

Firefox developer tools

Next in series, we have a hands-on video that shows how to use the developer tools in Firefox Developer Edition to debug and profile your game. Modifying code on the fly, adapting our game to different screen sizes, debugging… it’s all here!

Tips for game jams

Last, there is a video for all of you joining a game jam –these competitions where you develop a game over a weekend. I have participated in many, and I know first-hand how hard and challenging game jams are! I hope these tips might be of help.

And don’t forget, if you create an HTML 5 game, tell us about it here. I’d love to play 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)

From game jam to mobile and Firefox OS

I love participating in game jams, where game developers get together to craft games in a very short amount of time. I thought it would be cool to take one of my past Game Jam games, Metal vs Hipsters, and port it to the mobile web and Firefox OS.

Metal vs Hipsters (original)

Adapting to mobile

My starting point was an HTML5 game built for desktop. It had a fixed resolution, was controlled by the keyboard, etc. Some minor (and major!) tweaks would be required to make it a mobile game.

The game uses the open source game engine Phaser, so some of the code shown here will make use of Phaser’s API.

You can check out and play the final mobile version here.

Visualising the game

The first tool I used was Firefox’s Responsive Design View. It allows you to crop the screen and simulate different screen sizes. You can access it from the Firefox browser Tools drop-down menu under Tools>Web Developer>Responsive Design View.

The other tool was an actual mobile phone! I have an Android device with several browsers installed. By running the game in localhost and then connecting my phone to my local Wi-Fi network, I could access the game at my computer’s IP.

And this would yield the first problems…

Scaling

This is how bad the game looked in the responsive design view with no scaling at 320×480 size (landscape):

Scaling issues

The solution was to use Phaser’s ScaleManager to scale the game so it would fit well on the screen (with letter-boxing if needed):

var BootScene = {
  init: function () {
    // make the game occuppy all available space, but respecting
    // aspect ratio – with letterboxing if needed
    this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.game.scale.pageAlignHorizontally = true;
    this.game.scale.pageAlignVertically = true;
  },
  // ...
};

Furthermore, in the original game I used a wrapping div element to center the game on the page and also add some padding, text, etc. Now, all these page elements would have to be removed for the game to access all the available screen space.

Proper scale

Much better now!

Input

The next issue was controls. My desktop game used the arrow keys to move and jump the main character. I opted to include a virtual gamepad, so I created a new image for it:

Virtual gamepad

I needed three buttons: two for moving left and right and another one for jumping. I created three Phaser.Button instances. This was done in a helper function:

var upBtn = new Phaser.Button(this.game, ...);

Since Phaser.Button doesn’t have a flag that tells us whether a button is pressed or not, I needed to add it myself. This is easily done by listening to inputDown and inputUp events.

[leftBtn, rightBtn, upBtn].forEach(function (btn) {
  // register callbacks
  btn.isDown = false;
  btn.events.onInputDown.add(function () { btn.isDown = true; });
  btn.events.onInputUp.add(function () { btn.isDown = false; });

We also need to listen to the Up button’s inputDown, to enable the character to jump, since jumping in the desktop game was triggered by a keyDown event:

btnUp.events.onInputDown.add(this.tryJump, this);

For moving, it was just a matter of checking the isDown flag I’d already set, in addition to the previous check against the this.keys.left keyboard key.

if (this.keys.left.isDown || this.keys.btnLeft.isDown) {
  this.hero.move(-1);
}

Added virtual gamepad

The game was then playable on my device in the Firefox and Chrome for Android mobile browsers. However, play testing revealed even more issues…

Reposition elements

While I was playing the game I noticed that my own fingers would hide the game characters. This was a huge deal, since it made the game very difficult and annoying to play.

The solution was to make the group bigger (100 pixels) and then shift all the game elements up.

Reposition ground and characters

Allow tapping on additional areas

I also found out that tapping on the click to restart text was a bit hard. So I made the Game Over text, which was bigger, clickable too.

// create game over text
var banner = this.game.add.text(...);
banner.inputEnabled = true;
banner.events.onInputUp.add(this.restartGame, this);

In addition to that, I substituted click to restart for tap to restart, which makes more sense in mobile environments.

Revamping the splash screen

The splash screen needed some love too, since it was originally hardcoded to a fixed resolution.

The first step was to resize the background to take up the whole screen space, while maintaining its aspect ratio:

.overlay {
  background-size: cover;
}

Then I resized some of the existing text and buttons, and deleted the controls help diagram, since it referred to desktop arrow keys.

Splash screen

Re-playability

Finally, the game was fully playable… but now it was too short! The original game had five predefined waves of enemies. It was fine for the game jam, since most people only try the games for a very short amount of time (there are literally thousands of games to try out).

For a mobile game, one quick minute of gameplay is not good enough. So I tweaked the gameplay code to get rid of the predefined waves and make them random and infinite. Unlimited playtime!

Transform into a Firefox OS app

Once the game worked decently and was fun to play, it was time to turn it into a Firefox OS app.

Run in the simulator as a hosted app

The first step was to run it as a hosted app in a Firefox OS Simulator.

You can get the Simulator from the WebIDE (Tools > Web Developer > WebIDE) by clicking Install Simulator in the right sidebar. I installed Firefox OS version 2.6.

Install simulator

To create a hosted web app, we need an icon referenced in a JSON file with some metadata. This file is called the web app manifest.

While you can provide different sized icons, the minimum requirement is to have a 128x128 one:

Icon 128x128

The manifest file is just a JSON file in our app’s root. It contains some metadata about our app: the name of the app, the author, locales, etc. This is what the initial version of my manifest.webapp looked like.

{
  "name": "Metal vs Hipsters",
  "description": "Arcade game",
  "launch_path": "/index.html",
  "icons": {
    "128": "/images/icon-128.png"
  },
  "developer": {
    "name": "Belén 'Benko' Albeza",
    "url": "http://www.belenalbeza.com"
  },
  "default_locale": "en",
  "version": "1.0.0"
}

To run Metal vs Hipsters in the Simulator from the WebIDE, click on Open Hosted App and then point to the location of the manifest in the running local server:

Open Hosted App

Manifest URL

Now my project has been added…

Hosted web app

…and we can finally run it in the simulator.

Game running on simulator

Run in the phone as a packaged app

Running a game in the simulator is cool, but nothing beats playing your game on a real device. I wanted to create a packaged app in addition to a hosted app for Firefox Marketplace.

I had an Xperia Z3 Compact with Firefox OS on it ready for action. Once plugged in via USB and with developer mode enabled, it was listed in the WebIDE on the USB devices list.

Devices list

The workflow for creating a packaged app is very similar to the one I described for a hosted app. In the WebIDE click on Open Packaged App and then point to the game’s folder:

Packaged app

With my phone selected as a device, I clicked on the “play” button in the top bar and… boom!

Game running on Firefox OS phone

Now that I had the game running on a phone I could take advantage of some settings available only for apps and not just mobile websites. I wanted the game to run in fullscreen (without any prompting!) and I wanted to force a landscape orientation. I was able to do this by adding some more settings to the manifest.

{
 ...
  "fullscreen": "true",
  "orientation": ["landscape"]
}

Game running in fullscreen

Local assets

Now that I’d built the game as a packaged app, I needed to include all the assets needed to run it. The game uses one font from Google Fonts, Bangers. For the game jam, I included the font using one of Google’s suggested methods: linking to CSS on their servers that contains the font definition.

<link href='http://fonts.googleapis.com/css?family=Bangers'
 rel='stylesheet' type='text/css'>

As you can see, this won’t work for a packaged app, since it’s possible for a player to launch the game for the first time while offline, and they would not be able to access the font. Luckily, these fonts are also available for download and distribution with your projects (yay for open source!), so I did just that.

I copied the content of Google’s CSS file to my own CSS, changed the src URL to point to my local copy, and everything was set!

@font-face {
  font-family: 'Bangers';
  font-style: normal;
  font-weight: 400;
  src: url(../fonts/Bangers.woff2) format('woff2');
}

Into the Firefox Marketplace

Packaging for Firefox OS

A packaged app is distributed via a single zip file with our application on it. I was using a task runner, Gulp, to automate some parts of the development; so I added a new task to generate this zip file automatically. I made use of the gulp-zip module.

npm install gulp-zip --save
gulp.task('release', ['dist'], function () {
  var data = JSON.parse(fs.readFileSync('./package.json'));
  var filename = data.name + '-' + data.version + '.zip';

  return gulp.src('./dist/**/*')
    .pipe(zip(filename))
    .pipe(gulp.dest('.'));
});

Tip: once generated, always unzip your file to make sure everything is there!

Submitting your app to Firefox Marketplace

You can submit your app to the Marketplace, but you will need to create an account first.

Once logged in, I selected Free App, then Packaged and uploaded the zip file. Then the manifest and app files were validated.

App validation

There were some warnings related to the CSP, but since the game doesn’t ask for special permissions (like access to the contacts), it’ll be OK. These CSP warnings were due to Phaser using document.createElement('script') when using bitmap fonts. Since my game wasn’t using these fonts, I could just monkey patch Phaser and remove that code bit if I really needed special permissions for my game.

In order to submit the game, I had to provide a privacy policy. The game wasn’t collecting or storing any sort of data, so I settled by writing just that:

This application does not store or collect personal information or any kind of user data.

If your game does collect data, check out the privacy policy guidelines in the MDN to help you draft one.

I also needed some 320x480 screenshots:

Marketplace screenshot

As the last step, I was asked to setup content rating. The submission form takes you to the IARC tool, which is a wizard to help you rate your game depending on some criteria. Since my game features a form of fantasy violence –I guess a guitar of flames that destroys hipsters and cupcakes counts as so–, this ended up rated as PEGI-12.

PEGI rating

All done! Now time to wait a bit until it gets reviewed and approved.

More tweaks and potential improvements

Not all browsers have the same support of features or file formats. While testing the game in different devices, I found out some issues with Safari on iOS: the webfont wasn’t loaded properly and the background music tracks was not being played. The issue was that Safari for iOS doesn’t support neither Woff nor OGG as formats for fonts and audio (tip: you can check these things in Can I use?). All I had to add to be able to play the game in my iPad was to add those assets in TTF and MP4 as well.

The game should be playable in major major mobile browsers (Firefox, Chrome and Safari). I expect trouble with IE/Edge, but I don’t have a Windows device at hand to test this.

Although the current version is fun to play in browsers, there are other improvements that could make this a better game: use of the vibration API when the main character gets killed, store the high-score with localStorage, allow installation of the app directly from the game’s website, support for offline mode in the web version, etc.

Play!

The game is already available in the Firefox Marketplace for downloading. You can also play the game from your mobile browser here, and grab the full source code at Github as well.

I hope this article can help to port your HTML 5 games to mobile and Firefox OS. Most of the times they don’t need much tweaking and you could expand your player base. Plus playing your own game while commuting is priceless 🙂

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)

Power Surge – optimize the JavaScript in this HTML5 game using Firefox Developer Edition

Power Surge!

The Firefox Developer Tools team wanted to find a fun way to show off the great performance tools we’ve just added to the Firefox Developer Edition browser. We partnered with Przemys?aw Sikorski (aka rezoner) author of Playground.js and the arcade puzzle game QbQbQb, to create “Power Surge,” a fun game which shows off how the new Performance tools can help developers find slow JavaScript code. The special twist is that the more you optimize the code in the game, the more ships and powers you win in gameplay!

First off, check out this quick screencast from Mozilla engineer Harald Kirschner on how Power Surge works:

To get going with Power Surge:

We’d really like to hear back from you about Power Surge! Tweet to us at @FirefoxDevtools and @mozhacks to share your solutions.

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)

Resources for HTML5 game developers

Today we released Firefox 31 and it offers a couple of new features that help HTML5 game developers to code and debug sophisticated games. In addition Mozilla blogged about the first commercial games leveraging asm.js, Dungeon Defenders Eternity and Cloud Raiders both of which were cross-compiled in to JavaScript using the Emscripten compiler. Games like these show that HTML5 is ready as a game platform.

If you are interested in working with Emscripten you can get more information at the main Emscripten wiki or grab the code on the github page. Another good resource is the getting started with Emscripten tutorial on MDN. If you are wondering about the performance of asm.js, read asm.js performance improvements in the latest version of Firefox make games fly! for details.

In this post we’ll introduce you to some of the resources built by Mozillians that allow you to code and debug HTML5 based games. This list is not exhaustive and we appreciate feedback on any valuable resources that would help in this arena. Don’t be shy and tell us about them in the comments.

Where To Start

When developing an HTML5 based game, you have a lot of choices to make. These range from what editor to use, if the game will use Canvas 2d, WebGL, SVG, or CSS up to which specific rendering frameworks and game engines to use. Most of these decisions will be based on the developer experience and the platforms the game will be published on. No article will answer all these questions but we wanted to put together a post that would help get you started down the path.

One of the key resources available for game developers on MDN is the Games Zone. This section of MDN contains general game development articles, demos, external resources and examples. It also includes detailed descriptions of some of the APIs that a developer will need to be aware of when implementing an HMTL5 game, including sound management, networking, storage and graphics rendering. We are currently in the process of adding content and upgrading the zone. In the future we hope to have content and examples for most common scenarios, frameworks and tool chains.

In the meantime here are a few posts and MDN articles that help game developers getting started.

Tools

As an HTML5 developer you will have no shortage of tools at your disposal. In the Mozilla community we have been hard at work expanding the features that Firefox Developer Tools provide. These include a full-featured JavaScript Debugger, Style Editor, Page Inspector, Scratchpad, Profiler, Network Monitor and Web Console.

In addition to these, some notable tools have been updated or introduced recently and offer some great functionality for the game developer.

Canvas Debugger

With the current release of Firefox, we added a Canvas Debugger to the browser.
s_canvasdebugger
The Canvas Debugger allows you to trace through all canvas context calls that are used to generate a frame. Calls are color coded for specific calls for things like drawing elements or using a specific shader program. The Canvas Debugger is not only useful when developing a WebGL based game but can also be used when debugging a Canvas 2D based game. In the game below you can see in the animation strip as each image is drawn to the canvas. You can click any of these lines to get directly to the part of your JavaScript responsible for this action.
s_captainrogers
Two very common issues that have been reported when using the Canvas Debugger are with animations generated using setInterval instead of requestAnimationFrame and inspecting canvas elements in an iFrame.

To get more information about the Canvas Debugger be sure to read over Introducing the Canvas Debugger in Firefox Developer Tools.

Shader Editor

When developing WebGL based games it is very useful to be able to test and alter shader programs while the application is running. Using the Shader Editor within the developer tools makes this possible. Vertex and Fragment Shader programs can be modified without the need to reload the page, or black boxed to see what effect this has on the resulting output.
s_ShaderEditor

For more information on the Shader Editor, be sure to see Live editing WebGL shaders with Firefox Developer Tools post and take a look at this MDN article which contains a couple of videos showing live editing.

Web Audio Editor

The current version of Firefox Aurora (32) – has a Web Audio Editor. The Editor displays a graphical representation of all the Audio Nodes and their connections in the current AudioContext. You can drill down to specific attributes of each node to inspect them.
s_webaudioeditor

The Web Audio API provides more robust and complex sound creation, manipulation and processing than what is available in the HTML5 Audio tag. When using the Web Audio API make sure to read over Writing Web Audio API code that works in every browser as it contains pertinent information about support for the various audio nodes.

For more information on the Web Audio Editor be sure to read this Hacks article introducing the Web Editor and this MDN article.

Network Monitor

When developing an HTML5 based game network impact can be not only cumbersome but also costly if the user is on mobile device. Using the Network Monitor you can visually inspect all network request for location, time spent on the operation, and the type and size of the artifact.
s_networkmon
In addition you can use the Network Monitor to get a visual performance analysis of your app when cached versus non-cached.
s_networkcache

To get more information on the Network Monitor see the MDN page.

Web IDE

When starting your game one of your first choices will be which editor to use. And there are a lot of them (Sublime, Eclipse, Dreamweaver, vi, etc). In most cases a you already have a favorite. If you are interested in doing your development within the Browser you may want to have a look at the Web IDE that was recently released in Firefox Nightly.
s_webide

The Web IDE project provides not only a fully functional editor but also acts as a publishing agent to various local and remote platforms, debugger, template framework and application manager. In addition the framework supporting this project provides APIs that will allow other editors to use functionality provided in the tool. To get more details on the work that is being done in this area have a look at this post.

In order to keep up-to-date with news on the Firefox Developer Tools, follow their article series on the Hacks blog. For more detailed information on new, stable developer tools features, check out their documentation on MDN.

APIs

The MDN Games Zone lists various APIs and articles that are useful for beginning game development.
s_apis
In addition to these resources you may be interested in looking over some additional posts that can be valuable for development.

If your game is going to support multiplayer interaction using either WebRTC or WebSockets you may also be interested in looking at Together.js which provides collaborative features for web apps. To get an idea what is possible take a look at Introducing TogetherJS.

Many games will require storage and IndexedDB can be used to handle these needs. For information on extending the capabilities of IndexedDB read over Breaking the Borders of IndexedDB. You may also be interested in localForage which provides browser agnostic support for simple storage. To get more details about this library read over this Hacks post.

Game Optimization

HTML5 games today offer a great deal of power to the game developer. That said many of these games are going to be played on a mobile device, which in comparison to your desktop will pale in performance. So if you plan on your game being a success across platforms it is important that you optimize your code. The Optimizing your JavaScript Game for Firefox OS post has a lot of great techniques to help you build a game that performs well on low-end mobile devices.

Localization

In order to reach the most users of your game you may want to consider offering it in different languages. As part of this developers should start with localization built into the game. We are doing a great deal of work around recruiting translators to help you translate your game. To get more information about this initiative see this post.

Your Voice

As Mozilla is about the community of developers and users, we want your help and your feedback. If you have recommendations for specific features that you would like to see in the products make sure to either get involved in discussion on irc.mozilla.org or through our mailing lists. You can also log bugs at bugzilla.mozilla.org. In addition we are also provide additional feedback channels for our DevTools and Open Web Apps.

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)

Creating a Multiplayer Game with TogetherJS and CreateJS

Bubble Hell Duel is a multiplayer HTML5 dogfighting game. The object of the game is to dodge bubbles launched from your opponent while returning fire. This game was written mainly as a prototype for learning and the source code is available on GitHub. You can try the game out in single or multiplayer here. Currently the game does not contain any sound effects but uses CreativeJS and TogetherJS.

screenshot

In this post I would like to share some of my experiences when developing the game. Please share your thoughts in the comments if you agree or have other suggestions.

Game Engines

When developing a 2d game you can write you own engine or make use of some fantastic libraries that are available. After spending a few days looking at the various options available I decided to use CreateJS. As I have some experience with Flash, CreateJS made sense for my needs as there was not much of a learning curve. I also wanted to make use of some Flash animations and CreateJS supported this feature. I will elaborate a bit more on animations later in the article.

As I am a C++ developer I believe emscripten is also a good choice. It allows C/C++ code to be compiled to JavaScript, which can be executed in the browser. I am of the opinion that the static type checking and compile-time optimizations are great assets when developing large code bases. I have used emscripten before and it works very well, but for this project I wanted the fast and convenient prototyping capabilities of JavaScript. I also wanted to expand my JavaScript knowledge.

I’d like to mention a few other libraries that seem very interesting: Cocos2d-x is making an emscripten port and they already support HTML5 binding. I also like pixi.js as it provides a webGL renderer but also supports Canvas fallback when the browser does not support webGL.

C++ vs JavaScript

At first I was a little bit worried about the performance of JavaScript, and that was the reason my decision between using CreateJS or emscripten was difficult. Fortunately a simple benchmark showed that a naive collision detection algorithm with about 400 balls on screen could still reach 40+ fps, which was enough for my simple experiment.

As someone who has coded more in C++ than JavaScript I loved how quickly I could translate my thoughts into code and test them out on multiple browsers. On the other hand it was not very comfortable debugging my JavaScript. C++ compilers are quite good at pointing out misspellings and other mistakes that cause runtime issues. While the “use strict” directive and other mechanisms like closure compilers have their purpose they were not very helpful to me especially when variables became undefined. Rooting for the cause of errors can be somewhat difficult comparatively.

As an example of difficult debugging, I encountered the following issue. I was using float numbers for coordinates and other geometric values like angles. These values were passed to the other player using the TogetherJS.send method for synchronization:

var player = { x: 10.0, y: 10.0 };
TogetherJS.send({type:'sync',x:player.x,y:player.y});
TogetherJS.hub.on('sync', function(msg){
    enemy.x = msg.x;
    enemy.y = msg.y;
});

This worked, but lots of decimals were sent in this way, so I decided to relax the accuracy:

TogetherJS.send({type:'sync', x:Math.round(player.x), y:Math.round(player.y) });

Then I thought integers might not be accurate enough for collision detection, so I added more digits to the messages:

TogetherJS.send({type:'sync', x:player.x.toFixed(2), y:player.y.toFixed(2) });

While this seemed a reasonable solution, it actually induced a bug that was very hard to find and I did not notice it until I tested the game after implementing some more features. I noticed while playing the game the opponent would never move.

It took me hours in debugging before I could locate the cause. I do not think I would have made this mistake using C++.

If you would like to see this bug in action take a look at this jsFiddle project. Look at the three canvas tag outputs and you will notice the third canvas contains the bug. This issue occurs because toFixed returns a string representation.

I am not sure using a closure compiler would have avoided this issue, but I did find in another project that it definitely helps with optimizations.

Animation with Flash

As with most games I wanted to use a good deal of animation. I was very familiar with creating animations in Flash and found that CreateJS supported several ways of consuming the Flash animations and presenting them in HTML5. CreateJS is a set of libraries and tools used to create interactive HTML5 content. So by using CreateJS I could consume my animations as well as use the other libraries available for loop handling, resource management and in the future, sound manipulation. For a quick introduction to CreateJS take a look at this video.

CreateJS, which Mozilla now sponsors, offers great support for Flash animations.

There are two ways of using Flash animations in HTML5 with CreateJS. The first option is to directly export the Flash animation in a way that you can access all the elements in their original form, including paths, transformations and tweens. The advantage to this approach is that it produces smaller files, and CreateJS allows you to transfer them into a sprite sheet on the client side, for faster rendering. Adobe Flash CS6 offers the CreateJS Toolkit plugin that allows the designer to export all the content of an animation to HTML5 files. This generally results in a JavaScript file with all the graphics and tweens, an HTML file, and a set of image files. You can open up the HTML document in your browser and see the animation.

Another option is to export the animation into a sprite sheet, that is an image containing all the frames with a JavaScript file describing the position and size of each frame. These files can be easily integrated into HTML based games or applications via the SpriteSheet class in CreateJS. This is the approach I used for this game. To see the code where I use the SpriteSheet have a look at this link. If you want some more detail on this approach take a look at this video.

I should also note that you can use a tool called Zoë to export directly to a sprite sheet or a JSON file from a Flash Animation as well.

marisa

The above image is an example of a sprite sheet that I use in the game and was generated as described above. The original image came from the game Touhou Hisouten ~ Scarlet Weather Rhapsody, which is availabe at http://www.spriters-resource.com.

Multiplayer with TogetherJS

On my first iteration of the code the game was not multiplayer. Originally it was a single-player bullet hell game, with a boss foe randomly moving across the screen. I could not last more than 30 seconds before succumbing to withering fire. It was interesting enough that I thought multiplayer would be exciting.

I had heard of Together.js not long after it was released. The jsFiddle project is powered by Together.js and offers an impressive collaboration mode. This led me to using Together.js in my game. It is also very nice that Mozilla offers a default hub server simplifying the process of creating a multiplayer web based game. To learn more about Together.js be sure to check out this article.

It was easy and comfortable integrating Together.js into my game, as it works like other event dispatcher/listeners frameworks.

With Together.js, I was able to implement random match and invitation only multiplayer modes in the game. I did face a few design challenges that I had to overcome when designing the communication protocol.

First off, I did not put code in to prevent cheating with two-party communications and assumed a certain level of trust between players. In the game design currently all collision detection of a player is done locally. Theoretically if you block corresponding messages you can mask that you have taken damage.

Another area that I hacked a bit is that the bubbles of the enemy avatar are generated locally and randomly. This means that the bubbles seen from your character avatar are not necessarily the same as your opponent is seeing.

In practice neither of these shortcuts should ruin the fun of the game.
I did encounter a couple of issues or caveats with Together.JS.

  • I did not find a way to disable the cursor updating in Together.js. While this is useful in collaborative tools I did not need it in my game.
  • I am using Together.js in an asymmetric way, where both players see themselves as the red skirted Avatar (Reimu). This allows for easier placement of the player at the bottom of the screen and the opponent at the top. This also means that when you move the main player from an opponent’s view of the game your move is seen as the opponents move and vice versa.

The Fun of Making Mistakes

There are two visual effects in the game that came as unexpected surprises:

  • When a round finishes and the message ‘You Win’ or ‘You Lose’ appears, the time is frozen for a few seconds. This acts like a dramatic pause.
  • When a charge attack is released, the bullets are fixed and then gradually blown away toward the enemy.

Neither of these effects was designed in this way. I didn’t want the pause and I wanted the bullets to continue rotating around the player upon releasing. However I made mistakes, and the result seemed to be much better than I had planned, so they made the final cut.

Conclusion and Future Plans

It is always fun learning new things. I like the fact that I could prototype and visualize pretty quickly. In the future I might add more patterns for the bullet curtains, and a few sound effects. In addition I will probably also draw more background images or possibly animate them.

While developing the game I did realize in order to get a natural and intuitive feel required more effort than I expected. This is something I have always taken for granted while playing game.

The code is open source, so feel free to fork and play. Be sure to comment if you have any suggestions for improving the game or the existing code.

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)

The Pond – building a multi-platform HTML5 game

The Pond

Introducing The Pond

The Pond is a multi-platform HTML5 game (source code) that explores minimalistic design and resolution independent gameplay. The Pond isn’t about reaching a high score, or about buying weapon upgrades. It’s about relaxing and exploring a beautiful world.

It is available on all these platforms/in all these stores:

  • Firefox Marketplace
  • Google Play
  • Chrome Web Store
  • Amazon App store
  • Clay.io
  • Pokki

In making The Pond I came across many performance obstacles which I will explore in detail (especially when optimizing the codebase for mobile).

Tools

Before I begin, I would like to mention the two tools that made coding The Pond both efficient and highly enjoyable: Light Table and CocoonJS.

Light Table is an IDE (still in alpha) which provides an integrated development environment for real-time javascript code injection. This means that javascript edited within the editor can be previewed without reloading the page. If we look at the shape of the fish in the game we notice that it is comprised of Bézier curves. Instead of trying to find an editor for creating Bézier curves, I simply estimated a basic shape and modified the variables in real-time until I was satisfied with it’s look and feel.

CocoonJS on the otherhand provides a canvas optimized compatibility layer for improved performance on mobile devices. Not only does it optimize, it also provides an interface for exporting our application to many devices (Android, iOS, Amazon (android), Pokki, and Chrome Web Store).

Physics

The Pond may seem simple on the outside, but on the inside it’s full of performance optimizations and responsive features. As we resize the game, it updates and re-optimizes itself to render less objects and spawn less fish, and if that’s not enough the framerate degrades smoothly to keep physics in check. This is thanks to the use of a fixed interval physics time step. Gameprogrammingpatterns.com provides a good explanation for how to do this and why it matters, but honestly the code makes the most sense:

var MS_PER_UPDATE = 18; // Time between physics calculations
var lag = 0.0; // accumulate lag over frames
var previousTime = 0.0; // used for calculating the time delta
 
// main game loop
function draw(time) {
  requestAnimFrame(draw); // immidiately queue another frame
  lag += time - previousTime; // add time delta
  previousTime = time;
 
  var MAX_CYCLES = 18; // prevent infinite looping/hanging on slow machines
 
  // physics calculations
  while(lag >= MS_PER_UPDATE && MAX_CYCLES) {
 
    // user input, movement, and animation calculations
    physics();
    lag -= MS_PER_UPDATE;
    MAX_CYCLES--;
  }
 
  // if we exhausted our cycles, the client must be lagging
  if(MAX_CYCLES === 0) {
 
    // adaptive quality
    lowerQuality();
  }
 
  // if 5 frames behind after update, jump
  // this prevents an infinite input lag from ocurring
  if(lag/MS_PER_UPDATE > 75) {
    lag = 0.0;
  }
 
  // draw to canvas
  paint();
}

What’s important to notice here is that physics is not calculated based on the time delta, instead it’s calculated at a fixed 18ms interval. This is important because it means that any client lag will not be reflected in physics calculations, and that slower machines will simply lose framerate.

Dynamic Quality

The next optimization we notice is the lowerQuality() function, which adaptively decreases the render quality of the game. The way this works is simply by re-sizing the drawing canvas (it’s still full screen, it simply gets streched out), which in-turn leads to reduced spawns and collisions.

function resizeWindow() {
 
  // quality is a global variable, updated by lowerQuality()
  $canv.width = window.innerWidth * quality/10
  $canv.height = window.innerHeight * quality/10
  ctx = $canv.getContext('2d')
  ctx.lineJoin = 'round'
 
  // resize HUD elements, and reduce spawning
  if(GAME.state === 'playing') {
    GAME.spawner.resize($canv.width, $canv.height)
    GAME.levelBar.resize($canv.width, $canv.height)
    GAME.levelBalls.resize($canv.width, $canv.height)
  } else {
    if(ASSETS.loaded) drawMenu()
  }
}

Spawning

Now, we’ve been talking about reducing spawning to improve performance so let me explain how that happens. The spawning algorithm works by creating a virtual grid sized based on the window size. As the player travels from one grid zone to another, the adjacent zones are populated with enemies:

Grid Spawner

Spawner.prototype.spawn = function(zone) {
  // spawn 1-3  fish per 500sqpx, maybe larger maybe smaller than player
  // 0.5 chance that it will be bigger/smaller
  var mult = this.width*this.height/(500*500)
  for(var i=0, l=(Math.floor(Math.random()*3) + 1) * mult; i < l; i++) {
 
    // spawn coordinates random within a zone
    var x = zone[0]+Math.floor(this.width*Math.random()) - this.width/2
    var y = zone[1]+Math.floor(this.height*Math.random()) - this.height/2
    var size = Math.random() > 0.5 ? this.player.size + Math.floor(Math.random() * 10) : this.player.size - Math.floor(Math.random() * 10)
 
    // spawn a new fish
    var fish = new Fish(true, x, y, size, Math.random()*Math.PI*2-Math.PI, Math.random()*Math.PI)
 
    this.fishes.push(fish)
  }
  return zone
}

The last piece of the puzzle is removing enemies as they move far enough away:

// if far enough away from player, remove
if(distance(fish, player) > Math.max($canv.width, $canv.height) * 2) {
  fish.dead = true
}

Collisions

The next performance optimization lies with the collision code. Colliding irregularly shaped objects can be extremely difficult and resource intensive. One option is to do color based collision (scan for overlapping colors), but that is much too slow. Another option might be to mathematically calculate Bézier curve collisions, however this is not only CPU intensive, it is also quite difficult to code. I finally opted for an approximation approach using circles. Basically I calculate the position of circles within each fish and detect circle collision among the fish. Boolean circle collision is extremely efficient, as it simply requires measuring the distance between objects. This ends up looking like this (debug mode):

debug mode

Fish.prototype.collide = function (fish) {
 
  // the fish has been killed and is being removed or it is far away
  if (this.dying || fish.dying || distance(this, fish) > this.size * 5 + fish.size*5) {
    return false
  }
 
  // there are 6 circles that make up the collision box of each fish
  var c1, c2
  for (var i=-1, l = this.circles.length; ++i < l;) {
    c1 = this.circles[i]
    for (var j=-1, n = fish.circles.length; ++j < n;) {
      c2 = fish.circles[j]
 
      // check if they touch
      if(distance(c1, c2) <= c2.r + c1.r) {
        return true
      }
    }
  }
 
  return false
}

We also avoid unnecessary collision calculations by only checking the fish that are visible (or near-visible):

if(Math.abs(fish2.x - player.x) < $canv.width && Math.abs(fish2.y - player.y) < $canv.height) {
    // check
}

Drawing

After getting the physics+ out of the way, it’s time to optimize drawing operations. Many games use sprite maps for animation (Senshi for example) which can be highly optimized. Unfortunately our fish are dynamically generated so we must find other ways to optimizing drawing. First lets use Chrome’s javascript profiler to identify bottlenecks:

The Pond CPU profile

What we see here is that stroke is using a lot of resources. Truth be told, fill used to be there too. This is because both were called heavily when drawing fish. The game looked a bit like this:

The Pond - Old rendering

After removing fill I saw a huge performance increase, and the game looked much better. The reason the drawImage function is up there as well is because I take advantage of offscreen canvas rendering. Each fish is drawn on its own offscreen canvas which is then rendered onto the larger visible canvas. This is also what allowed me to easily explode the fish into particles by reading pixel data:

Fish.prototype.toParticles = function(target) {
  var particles = []
 
  // read canvas pixel data
  var pixels = this.ctx.getImageData(0,0,this.canv.width, this.canv.height).data
  for(var i = 0; i < pixels.length; i += 36 * Math.ceil(this.size/20) * (isMobile ? 6 : 1)) {
    var r = pixels[i]
    var g = pixels[i + 1]
    var b = pixels[i + 2]
 
    // black pixel - no data
    if(!r && !g && !b){
      continue
    }
 
    // Math to calculate position
    var x = i/4 % this.canv.width - (this.canv.width/2 + this.size)
    var y = Math.floor(i/4 / this.canv.width) - (this.canv.height/2)
    var relativePos = rot(x, y, this.dir)
    x=this.x + relativePos[0]
    y=this.y + relativePos[1]
 
    var col = new Color(r, g, b)
    var dir = directionTowards({x: x, y: y}, this)
    particles.push(new Particle(x, y, col, target, Math.PI*Math.random()*2 - Math.PI, this.size/20))
  }
  return particles
}

The End

In the end the performance optimizations paid off and made the game feel more polished and playable even on lower-end mobile devices.

If you enjoyed this post, I regularly blog about my development projects over at http://zolmeister.com.

The Pond awaits exploring…

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)

An AR Game: Technical Overview

An AR Game is the winning entry for the May 2013 Dev Derby. It is an augmented reality game, the objective being to transport rolling play pieces from a 2D physics world into a 3D space. The game is playable on GitHub, and demonstrated on YouTube. The objective of this article is to describe the underlying approaches to the game’s design and engineering.

Technically the game is a simple coupling of four sophisticated open source technologies: WebRTC, JSARToolkit, ThreeJS, and Box2D.js. This article describes each one, and explains how we weaved them together. We will work in a stepwise fashion, constructing the game from the ground up. The code discussed in this article is available on github, with a tag and live link for each tutorial step. Specific bits of summarized source will be referenced in this document, with the full source available through the ‘diff’ links. Videos demonstrating application behaviour are provided where appropriate.

git clone https://github.com/abrie/devderby-may-2013-technical.git

This article will first discuss the AR panel (realspace), then the 2D panel (flatspace), and conclude with a description of their coupling.

Panel of Realspace

Realspace is what the camera sees — overlaid with augmented units.

Begin with a Skeleton

git checkout example_0
live, diff, tag

We will organize our code into modules using RequireJS. The starting point is a main module with two skeletal methods common to games. They are initialize() to invoke startup, and tick() for rendering every frame. Notice that the gameloop is driven by repeated calls to requestAnimationFrame:

requirejs([], function() {
 
    // Initializes components and starts the game loop
    function initialize() {
    }
 
    // Runs one iteration of the game loop
    function tick() {
        // Request another iteration of the gameloop
        window.requestAnimationFrame(tick);
    }
 
    // Start the application
    initialize();
    tick();
});

The code so far gives us an application with an empty loop. We will build up from this foundation.

Give the Skeleton an Eye

git checkout example_1
live, diff, tag

AR games require a realtime video feed: HTML5‘s WebRTC provides this through access to the camera, thus AR games are possible in modern browsers like Firefox. Good documentation concerning WebRTC and getUserMedia may be found on developer.mozilla.org, so we won’t include the basics here.

A camera library is provided in the form of a RequireJS module named webcam.js, which we’ll incorporate into our example.

First the camera must be initialized and authorized. The webcam.js module invokes a callback on user consent, then for each tick of the gameloop a frame is copied from the video element to a canvas context. This is important because it makes the image data accessible. We’ll use it in subsequent sections, but for now our application is simply a canvas updated with a video frame at each tick.

Something Akin to a Visual Cortex

git checkout example_2
live, diff, tag

JSARToolkit is an augmented reality engine. It identifies and describes the orientation of fiducial markers in an image. Each marker is uniquely associated with a number. The markers recognized by JSARToolkit are available here as PNG images named according to their ID number (although as of this writing the lack of PNG extensions confuses Github.) For this game we will use #16 and #32, consolidated onto a single page:

JSARToolkit found its beginnings as ARToolkit, which was written in C++ at the Univeristy of Washington‘s HITLab in Seattle. From there it has been forked and ported to a number of languages including Java, then from Java to Flash, and finally from Flash to JS. This ancestry causes some idiosyncrasies and inconsistent naming, as we’ll see.

Let’s take a look at the distilled functionality:

 // The raster object is the canvas to which we are copying video frames.
 var JSARRaster = NyARRgbRaster_Canvas2D(canvas);
 
 // The parameters object specifies the pixel dimensions of the input stream.
 var JSARParameters = new FLARParam(canvas.width, canvas.height);
 
 // The MultiMarkerDetector is the marker detection engine
 var JSARDetector = new FLARMultiIdMarkerDetector(FLARParameters, 120);
 JSARDetector.setContinueMode(true);
 
 // Run the detector on a frame, which returns the number of markers detected.
 var threshold = 64;
 var count = JSARDetector.detectMarkerLite(JSARRaster, threshold);

Once a frame has been processed by JSARDetector.detectMarkerLite(), the JSARDetector object contains an index of detected markers. JSARDetector.getIdMarkerData(index) returns the ID number, and JSARDetector.getTransformMatrix(index) returns the spatial orientation. Using these methods is somewhat complicated, but we’ll wrap them in usable helper methods and call them from a loop like this:

var markerCount = JSARDetector.detectMarkerLite(JSARRaster, 90); 
 
for( var index = 0; index &lt; markerCount; index++ ) {
    // Get the ID number of the detected marker.
    var id = getMarkerNumber(index);
 
    // Get the transformation matrix of the detected marker.
    var matrix = getTransformMatrix(index);
}

Since the detector operates on a per-frame basis it is our responsibility to maintain marker state between frames. For example, any of the following may occur between two successive frames:

  • a marker is first detected
  • an existing marker’s position changes
  • an existing marker disappears from the stream.

The state tracking is implemented using ardetector.js. To use it we instantiate a copy with the canvas receiving video frames:

// create an AR Marker detector using the canvas as the data source
var detector = ardetector.create( canvas );

And with each tick the canvas image is scanned by the detector, triggering callbacks as needed:

// Ask the detector to make a detection pass. 
detector.detect( onMarkerCreated, onMarkerUpdated, onMarkerDestroyed );

As can be deduced from the code, our application now detects markers and writes its discoveries to the console.

Reality as a Plane

git checkout example_3
live, diff, tag

An augmented reality display consists of a reality view overlaid with 3D models. Rendering such a display normally consists of two steps. The first is to render the reality view as captured by the camera. In the previous examples we simply copied that image to a canvas. But we want to augment the display with 3D models, and that requires a WebGL canvas. The complication is that a WebGL canvas has no context into which we can copy an image. Instead we render a textured plane into the WebGL scene, using images from the webcam as the texture. ThreeJS can use a canvas as a texture source, so we can feed the canvas receiving the video frames into it:

// Create a texture linked to the canvas.
var texture = new THREE.Texture(canvas);

ThreeJS caches textures, therefore each time a video frame is copied to the canvas a flag must be set to indicate that the texture cache should be updated:

// We need to notify ThreeJS when the texture has changed.
function update() {
    texture.needsUpdate = true;
}

This results in an application which, from the perspective of a user, is no different than example_2. But behind the scenes it’s all WebGL; the next step is to augment it!

Augmenting Reality

git checkout example_4
live, diff, tag, movie

We’re ready to add augmented components to the mix: these will take the form of 3D models aligned to markers captured by the camera. First we must allow the ardector and ThreeJS to communicate, and then we’ll be able to build some models to augment the fiducial markers.

Step 1: Transformation Translation

Programmers familiar with 3D graphics will know that the rendering process requires two matrices: the model matrix (transformation) and a camera matrix (projection). These are supplied by the ardetector we implemented earlier, but they cannot be used as is — the matrix arrays provided by ardetector are incompatible with ThreeJS. For example, the helper method getTransformMatrix() returns a Float32Array, which ThreeJS does not accept. Fortunately the conversion is straightforward and easily done through a prototype extension, also known as monkey patching:

// Allow Matrix4 to be set using a Float32Array
THREE.Matrix4.prototype.setFromArray = function(m) {
 return this.set(
  m[0], m[4], m[8],  m[12],
  m[1], m[5], m[9],  m[13],
  m[2], m[6], m[10], m[14],
  m[3], m[7], m[11], m[15]
 );
}

This allows us to set the transformation matrix, but in practice we’ll find that updates have no effect. This is because of ThreeJS’s caching. To accommodate such changes we construct a container object and set the matrixAutoUpdate flag to false. Then for each update to the matrix we set matrixWorldNeedsUpdate to true.

Step 2: Cube Marks the Marker

Now we’ll use our monkey patches and container objects to display colored cubes as augmented markers. First we make a cube mesh, sized to fit over the fiducial marker:

function createMarkerMesh(color) {
    var geometry = new THREE.CubeGeometry( 100,100,100 );
    var material = new THREE.MeshPhongMaterial( {color:color, side:THREE.DoubleSide } );
 
    var mesh = new THREE.Mesh( geometry, material );                      
 
    //Negative half the height makes the object appear "on top" of the AR Marker.
    mesh.position.z = -50; 
 
    return mesh;
}

Then we enclose the mesh in the container object:

function createMarkerObject(params) {
    var modelContainer = createContainer();
 
    var modelMesh = createMarkerMesh(params.color);
    modelContainer.add( modelMesh );
 
    function transform(matrix) {
        modelContainer.transformFromArray( matrix );
    }
}

Next we generate marker objects, each one corresponding to a marker ID number:

// Create marker objects associated with the desired marker ID.
    var markerObjects = {
        16: arobject.createMarkerObject({color:0xAA0000}), // Marker #16, red.
        32: arobject.createMarkerObject({color:0x00BB00}), // Marker #32, green.
    };

The ardetector.detect() callbacks apply the transformation matrix to the associated marker. For example, here the onCreate handler adds the transformed model to the arview:

// This function is called when a marker is initally detected on the stream
function onMarkerCreated(marker) {
    var object = markerObjects[marker.id];
 
    // Set the objects initial transformation matrix.
    object.transform( marker.matrix );
 
    // Add the object to the scene.
    view.add( object );
}
});

Our application is now a functioning example of augmented reality!

Making Holes

In An AR Game the markers are more complex than coloured cubes. They are “warpholes”, which appear to go -into- the marker page. The effect requires a bit of trickery, so for the sake of illustration we’ll construct the effect in three steps.

Step 1: Open the Cube

git checkout example_5
live, diff, tag, movie

First we remove the top face of the cube to create an open box. This is accomplished by setting the face’s material to be invisible. The open box is positioned behind/underneath the marker page by adjusting the Z coordinate to half of the box height.

The effect is interesting, but unfinished — and perhaps it is not immediately clear why.

Step 2: Cover the Cube in Blue

git checkout example_6
live, diff, tag, movie

So what’s missing? We need to hide the part of the box which juts out from ‘behind’ the marker page. We’ll accomplish this by first enclosing the box in a slightly larger box. This box will be called an “occluder”, and in step 3 it will become an invisibility cloak. For now we’ll leave it visible and colour it blue, as a visual aid.

The occluder objects and the augmented objects are rendered into the same context, but in separate scenes:

function render() {
    // Render the reality scene
    renderer.render(reality.scene, reality.camera);
 
    // Render the occluder scene
    renderer.render( occluder.scene, occluder.camera);
 
    // Render the augmented components on top of the reality scene.
    renderer.render(virtual.scene, virtual.camera);
}

This blue jacket doesn’t yet contribute much to the “warphole” illusion.

Step 3: Cover the Cube In Invisibility

git checkout example_7
live, diff, tag, movie

The illusion requires that the blue jacket be invisible while retaining its occluding ability — it should be an invisible occluder. The trick is to deactivate the colour buffers, thereby rendering only to the depth buffer. The render() method now becomes:

function render() {
    // Render the reality scene
    renderer.render(reality.scene, reality.camera);
 
    // Deactivate color and alpha buffers, leaving only depth buffer active.
    renderer.context.colorMask(false,false,false,false);
 
    // Render the occluder scene
    renderer.render( occluder.scene, occluder.camera);
 
    // Reactivate color and alpha buffers.
    renderer.context.colorMask(true,true,true,true);
 
    // Render the augmented components on top of the reality scene.
    renderer.render(virtual.scene, virtual.camera);
}

This results in a much more convincing illusion.

Selecting Holes

git checkout example_8
live, diff, tag

An AR Game allows the user to select which warphole to open by positioning the marker underneath a targeting reticule. This is a core aspect of the game, and it is technically known as object picking. ThreeJS makes this a fairly simple thing to do. The key classes are THREE.Projector() and THREE.Raycaster(), but there is a caveat: despite the key method having a name of Raycaster.intersectObject(), it actually takes a THREE.Mesh as the parameter. Therefore we add a mesh named “hitbox” to createMarkerObject(). In our case it is an invisible geometric plane. Note that we are not explicitly setting a position for this mesh, leaving it at the default (0,0,0), relative to the markerContainer object. This places it at the mouth of the warphole object, in the plane of the marker page, which is where the face we removed would be if we hadn’t removed it.

Now we have a testable hitbox, we make a class called Reticle to handle intersection detection and state tracking. Reticle notifications are incorporated into the arview by including a callback when we add an object with arivew.add(). This callback will be invoked whenever the object is selected, for example:

view.add( object, function(isSelected) {
    onMarkerSelectionChanged(marker.id, isSelected);
});

The player is now able to select augmented markers by positioning them at the center of the screen.

Refactoring

git checkout example_9
live, diff, tag

Our augmented reality functionality is essentially complete. We are able to detect markers in webcam frames and align 3D objects with them. We can also detect when a marker has been selected. We’re ready to move on to the second key component of An AR Game: the flat 2D space from which the player transports play pieces. This will require a fair amount of code, and some preliminary refactoring would help keep everything neat. Notice that a lot of AR functionality is currently in the main application.js file. Let’s excise it and place it into a dedicated module named realspace.js, leaving our application.js file much cleaner.

Panel of Flatspace

git checkout example_10
live, diff, tag

In An AR Game the player’s task is to transfer play pieces from a 2D plane to a 3D space. The realspace module implemented earlier serves as the the 3D space. Our 2D plane will be managed by a module named flatspace.js, which begins as a skeletal pattern similar to those of application.js and realspace.js.

The Physics

git checkout example_11
live, diff, tag

The physics of the realspace view comes free with nature. But the flatspace pane uses simulated 2D physics, and that requires physics middleware. We’ll use a JavaScript transpilation of the famous Box2D engine named Box2D.js. The JavaScript version is born from the original C++ via LLVM, processed by emscripten.

Box2D is a rather complex piece of software, but well documented and well described. Therefore this article will, for the most part, refrain from repeating what is already well-documented in other places. We will instead describe the common issues encountered when using Box2D, introduce a solution in the form of a module, and describe its integration into flatspace.js.

First we build a wrapper for the raw Box2D.js world engine and name it boxworld.js. This is then integrated into flatspace.

This does not yield any outwardly visible affects, but in reality we are now simulating an empty space.

The Visualization

It would be helpful to be able to see what’s happening. Box2D thoughtfully provides debug rendering, and Box2D.js facilitates it through something like virtual functions. The functions will draw to a canvas context, so we’ll need to create a canvas and then supply the VTable with draw methods.

Step 1: Make A Metric Canvas

git checkout example_12
live, diff, tag

The canvas will map a Box2D world. A canvas uses pixels as its unit of measurement, whereas Box2D describes its space using meters. We’ll need methods to convert between the two, using a pixel-to-meter ratio. The conversion methods use this constant to convert from pixels to meters, and from meters to pixels. We also align the coordinate origins. These methods are associated with a canvas and all are wrapped into the boxview.js module. This makes it easy to incorporate it into flatspace:

It is instantiated during initialization, its canvas then added to the DOM:

view = boxview.create({
    width:640, 
    height:480,
    pixelsPerMeter:13,
});
 
document.getElementById("flatspace").appendChild( view.canvas );

There are now two canvases on the page ‐ the flatspace and the realspace. A bit of CSS in application.css puts them side-by-side:

#realspace {
    overflow:hidden;
}
 
#flatspace {
    float:left;
}

Step 2: Assemble A Drafting Kit

git checkout example_13
live, diff, tag

As mentioned previously, Box2D.js provides hooks for drawing a debug sketch of the world. They are accessed via a VTable through the customizeVTable() method, and subsequently invoked by b2World.DrawDebugData(). We’ll take the draw methods from kripken’s description, and wrap them in a module called boxdebugdraw.js.

Now we can draw, but have nothing to draw. We need to jump through a few hoops first!

The Bureaucracy

A Box2D world is populated by entities called Bodies. Adding a body to the boxworld subjects it to the laws of physics, but it must also comply with the rules of the game. For this we create a set of governing structures and methods to manage the population. Their application simplifies body creation, collision detection, and body destruction. Once these structures are in place we can begin to implement the game logic, building the system to be played.

Creation

git checkout example_14
live, diff, tag

Let’s liven up the simulation with some creation. Box2D Body construction is somewhat verbose, involving fixtures and shapes and physical parameters. So we’ll stow our body creation methods in a module named boxbody.js. To create a body we pass a boxbody method to boxworld.add(). For example:

function populate() {
    var ball = world.add(
        boxbody.ball,
        {
            x:0,
            y:8,
            radius:10
        }
    );
}

This yields an undecorated ball in midair experiencing the influence of gravity. Under contemplation it may bring to mind a particular whale.

Registration

git checkout example_15
live, diff, tag

We must be able to keep track of the bodies populating flatworld. Box2D provides access to a body list, but it’s a bit too low level for our purposes. Instead we’ll use a field of b2Body named userData. To this we assign a unique ID number subsequently used as an index to a registry of our own design. It is implemented in boxregistry.js, and is a key aspect of the flatspace implementation. It enables the association of bodies with decorative entities (such as sprites), simplifies collision callbacks, and facilitates the removal of bodies from the simulation. The implementation details won’t be described here, but interested readers can refer to the repo to see how the registry is instantiated in boxworld.js, and how the add() method returns wrapped-and-registered bodies.

Collision

git checkout example_16
live, diff, tag

Box2D collision detection is complicated because the native callback simply gives two fixtures, raw and unordered, and all collisions that occur in the world are reported, making for a lot of conditional checks. The boxregistry.js module avails itself to managing the data overload. Through it we assign an onContact callback to registered objects. When a Box2D collision handler is triggered we query the registry for the associated objects and check for the presence of a callback. If the object has a defined callback then we know its collision activity is of interest. To use this functionality in flatspace.js, we simply need to assign a collision callback to a registered object:

function populate() {
    var ground = world.add(
        boxbody.edge,
        {
            x:0,
            y:-15,
            width:20,
            height:0,
        }
    );
 
    var ball = world.add(
        boxbody.ball,
        {
            x:0,
            y:8,
            radius:10
        }
    );
 
    ball.onContact = function(object) {
        console.log("The ball has contacted:", object);
    };
}

Deletion

git checkout example_17
live, diff, tag

Removing bodies is complicated by the fact that Box2D does not allow calls to b2World.DestroyBody() from within b2World.Step(). This is significant because usually you’ll want to delete a body because of a collision, and collision callbacks occur during a simulation step: this is a conundrum! One solution is to queue bodies for deletion, then process the queue outside of the simulation step. The boxregistry addresses the problem by furnishing a flag, isMarkedForDeletion, for each object. The collection of registered objects is iterated and listeners are notified of the deletion request. The iteration happens after a simulation step, so the deletion callback cleanly destroys the bodies. Perceptive readers may notice that we are now checking the isMarkedForDeletion flag before invoking collision callbacks.

This happens transparently as far as flatspace.js is concerned, so all we need to do is set the deletion flag for a registered object:

ball.onContact = function(object) {
    console.log("The ball has contacted:", object);
    ball.isMarkedForDeletion = true;
};

Now the body is deleted on contact with the ground.

Discerning

git checkout example_18
live, diff, tag

When a collision is detected An AR Game needs to know what the object has collided with. To this end we add an is() method for registry objects, used for comparing objects. We will now add a conditional deletion to our game:

ball.onContact = function(object) {
    console.log("The ball has contacted:", object);
    if( object.is( ground ) ) {
        ball.isMarkedForDeletion = true;
    }
};

A 2D Warphole

git checkout example_19
live, diff, tag

We’ve already discussed the realspace warpholes, and now we’ll implement their flatspace counterparts. The flatspace warphole is simply a body consisting of a Box2D sensor. The ball should pass over a closed warphole, but through an open warphole. Now imagine an edge case where a ball is over a closed warphole which is then opened up. The problem is that Box2D’s onBeginContact handler behaves true to its name, meaning that we detected warphole contact during the closed state but have since opened the warphole. Therefore the ball is not warped, and we’re left with a bug. Our fix is to use a cluster of sensors. With a cluster there will be a series of BeginContact events as the ball moves across the warphole. Thus we can be confident that opening a warphole while the ball is over it will result in a warp. The sensor cluster generator is named hole and is implemented in boxbody.js. The generated cluster looks like this:

The Conduit

At this point we’ve made JSARToolkit and Box2D.js into usable modules. We’ve used them to create warpholes in realspace and flatspace. The objective of An AR Game is to transport pieces from flatspace to the realspace, so it is necessary that the warpholes communicate. Our approach is as follows:

  1. git checkout example_20
    live, diff, tag

    Notify the application when a realspace warphole’s state changes.

  2. git checkout example_21
    live, diff, tag

    Set flatspace warphole states according to realspace warphole states.

  3. git checkout example_22
    live, diff, tag

    Notify the application when a ball transits an open flatspace warphole.

  4. git checkout example_23
    live, diff, tag

    Add a ball to realspace when the application receives a notification of a transit.

Conclusion

This article has shown the technical underpinnings of An AR Game. We have constructed two panes of differing realities and connected them with warpholes. A player may now entertain him or herself by transporting a ball from flatspace to realspace. Technically this is interesting, but generally it is not fun!

There is still much to be done before this application becomes a game, but they are outside the scope of this article. Among the remaining tasks are:

  • Sprites and animations.
  • Introduce multiple balls and warpholes.
  • Provide a means of interactively designing levels.

Thanks for reading! We hope this has inspired you to delve into this topic more!

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)

Getting Started With HTML5 Game Development

There are plenty of valid ways to create an HTML5 game, and quite a bit of material on the technical aspect of each, so for this article I’ll be giving more of a broad overview of HTML5 game development. How “HTML5″ can be better than native, where to start with the development process, where to go when you’re stuck, and how to monetize and distribute games.

Benefits of HTML5

Most of the audience here already sees the value in HTML5, but I want to re-iterate why you should be building an HTML5 game. If you are just targeting iOS for your game, write the game in Objective-C, the cons outweigh the benefits in that scenario… but if you want to build a game that works on a multitude of platforms, HTML5 is the way to go.

Cross-Platform

One of the more obvious advantages of HTML5 for games is that the games will work on any modern device. Yes, you will have to put extra thought into how your game will respond to various screen sizes and input types, and yes, you might have to do a bit of ‘personalization’ in the code per platform (the main inhibitor being audio); but it’s far better than the alternative of completely porting the game each time.

I see too many games that don’t work on mobile and tablets, and in most instances that really is a huge mistake to make when developing your game – keep mobile in mind when developing your HTML5 game!

Unique Distribution

Most HTML5 games that have been developed to this point are built in the same manner as Flash and native mobile games. To some extent this makes sense, but what’s overlooked is the actual benefits The Web as a platform adds. It’s like if an iOS developer were to build a game that doesn’t take advantage of how touch is different from a mouse – or if Doodle Jump was built with arrow keys at the bottom of the screen instead of using the device’s accelerator.

It’s so easy to fall into the mindset of doing what has worked in the past, but that stifles innovation. It’s a trap I’ve fallen into – trying to 100% emulate what has been successful on iOS, Android, and Flash – and it wasn’t until chatting with former Mozillian Rob Hawkes before I fully realized it. While emulating what worked in the past is necessary to an extent, The Open Web is a different vehicle for games, and innovation can only happen when taking a risk and trying something new.

Distribution for HTML5 games is often thought of as a weakness, but that’s just because we’ve been looking at it in the same sense as native mobile games, where a marketplace is the only way to find games. With HTML5 games you have the incredible powerful hyperlink. Links can so easily be distributed across the web and mobile devices (think of how many links you click in the Facebook and Twitter apps), and it certainly should not just be limited to the main page for the game. The technology is there to be able to link to your game and do more interesting things like jump to a specific point in a game, try to beat a friend’s score, or play real-time against that friend – use it to your advantage!

Take a good look at was has worked for the virality of websites and apply those same principles to your games.

Quicker Development Process

No waiting for compilation, updates and debugging in real-time, and once the game is done, you can push out the update immediately.

Choosing a Game Engine

Game engines are just one more level of abstraction that take care of a few of the more tedious tasks of game development. Most take care of asset loading, input, physics, audio, sprite maps and animation, but they vary quite a bit. Some engines are pretty barebones, while some (ImpactJS for example) go as far as including a 2D level editor and debug tools.

Decide Whether or Not You Need a Game Engine

This is largely a personal decision. Game Engines will almost always reduce the time it takes for you to create a fully-functional game, but I know some folks just like the process of building everything from the ground up so they can better understand every component of the game.

For simple games, it really isn’t difficult to build from scratch (assuming you have a JavaScript background and understand how games work). Slime Volley (source) for example was built without having a game engine, and none of the components were rocket science. Of course, Slime Volley is a very basic game, building an RPG from the ground up would likely lead to more hair pulling.

Choosing Between a “Game Engine” and a “Game Maker”

Most of the typical audience of Mozilla Hacks are probably going to lean toward using a game engine or building from scratch, but there is also the alternative of using a “Game Maker” like Construct 2. Using a Game Maker means you won’t actually write in JavaScript; instead, you create code-like events in the editor. It’s a trade of ease-of-use and quickness to prototype/develop vs customization and control over the end result. I’ve seen some very impressive games built with either, but as a developer-type, I tend to favor writing from scratch / using an engine.

Finding the Right Game Engine / Game Maker for you

There are so many HTML5 game engines out there, which in part is a good thing, but can also be a bad thing since a large percentage have either already stopped being maintained, or will soon stop being maintained. You definitely want to pick an engine that will continually be updated and improved over the years to come.

HTML5GameEngine.com is a great place to start your search because the hundreds of game engines are narrowed down to about 20 that are established, actively maintained, and have actual games being developed with them.

For a more complete list of engines (meaning there can be some junk to sift through), this list on GitHub is your best bet.

Learning Tools

If you’re going with a game engine, typically their site is the best resource with tutorials and documentation.

Technical Tutorials

Game Design Tutorials

With game development, the technical aspect isn’t everything – what’s more important is that the game actually be fun. Below are a few places to start when learning about game mechanics.

Helpful Game Tools

User Retention, Monetization and more

Full disclosure here: I am a co-founder at Clay.io.

Making a game function is just part of the equation. You also want players to play longer, come back, tell their friends about it, and maybe even buy something. Common elements in games that focus on these areas are features like user accounts, high scores, achievements, social integration, and in-game payments. On the surface most are typically easy enough to implement, but there are often many cross-platform issues and intricacies that are overlooked. There is also value in having a central service running these across many games – for example, players genuinely care about achievements on Xbox Live because Gamerscore matters to them.

  • Clay.io – user accounts, high scores, achievements, in-game payments, analytics, distribution, and more.
  • Scoreoid – similar to above.

Development Tools

  • stats.js – A JavaScript performance monitor. Displays framerate, and performance over time.
  • Socket.IO – realtime client-server communication (if you’re going to have a backend for your game).
  • pixi.js – A canvas and WebGL rendering engine.
  • CocoonJS – Improves HTML5 game performance on iOS and Android with an accelerated canvas bound to OpenGL ES.

Motivation

Regardless of what you’re building, extra motivation is always helpful. For games, that motivation often comes from surrounding yourself with others who are in the same boat as you – working on games.

js13kGames

js13kGames is a competition that is currently taking place at the time of this writing. You have until September 13th, 2013 to develop an HTML5 game that, when compressed, is less than 13kb.

Mozilla Game On

Mozilla runs a game competition every year from December through February with some fantastic prizes – last year’s was an all-expense paid, red carpet trip to San Francisco for GDC 2013.

Clay.io’s “Got Game?”

Clay.io (full disclosure, I am a founder) runs an annual HTML5 game development competition for students. Last year was the first year and we had over 70 games submitted. The next competition is planned for February / March 2014.

Ludum Dare

Ludum Dare isn’t for tangible prizes, nor is is specific to HTML5 games, but there are plenty of HTML5 developers that participate.

One Game a Month

One Game a Month isn’t so much a competition as it is an accountability tool. This isn’t restricted to HTML5 games, but many of the participants work with HTML5. The goal is to crank out one game every month. I wouldn’t recommend this long-term since one month is too short of a time to create a great game, but it’s good when learning to force yourself to develop and finish simple games.

Help From the Community

HTML5GameDevs.com

HTML5GameDevs has quickly become the most active community of HTML5 game developers. Most folks are very friendly and willing to help with any issues you run into.

#BBG

#BBG is the go-to IRC channel for HTML5 games – you’ll even find quite a few Mozillians hanging around.

How to Make Money

In-Game Purchases

In-game payments, in my opinion, are the way to go for HTML5 game in the long-term. For now, most HTML5 games don’t have enough quality content, nor the game mechanics in place to get player purchasing items.

This is the revenue model with the highest potential, but it’s also the most difficult to achieve by far – not technically, but having the right game. I’d say the best way to learn how to properly monetize your game in this aspect is to take a look at games that do it really well on Flash and Mobile – games from King.com and Zynga typically have this nailed down pretty well. There’s also some good reading material, like The Top F2P Monetization Tricks on Gamasutra.

Licensing

Where we’re at right now with HTML5 games, licensing games is the strongest, most consistent way to make money – if and only if your game works well on mobile devices.

There are countless “Flash Game Portals” that receive organic mobile traffic, but can’t monetize it with the Flash games they have. Their solution is to go out and find HTML5 games to buy non-exclusive licenses (the right to put the game on their site, often making small adjustments) to offer their mobile visitors.

Typically non-exclusive HTML5 game licenses (meaning you can sell to more than one site) go for $500-$1,000 depending on the game and publisher. Some publishers will do a revenue share model instead where you’ll get a 40-50% share on any advertising revenue, but no up-front money.

Licensing is the safest way to make money right now, but the cap is limited – the most you’re going to make with a single game is in the $5,000-$6,000 range, but it is easier to hit that mark than it is with in-game payments or advertising.

Advertising

Advertising is the middle-ground between in-game payments and licensing. It’s easier than in-game payments to make money and with a higher potential cap than licensing (but probably less than in-game payments). It’s easy enough to implement ads: just pick your ad network of choice (be wary of Adsense’s strict terms) and implement them either surrounding the game, or at various stopping points.

The commonly used ad networks are LeadBolt for mobile and CPMStar for desktop. You can also use Clay.io which makes it a bit easier to implement advertising, and tries to maximize the revenue by using different ad networks depending on the device used and other factors.

Distribution

The final stage in a game’s development is distribution. The game is done, now you want people playing the game! Fortunately, with HTML5 there are plenty of places to have your game (many of which often go unused).

More and more marketplaces these days are accepting HTML5 games as-is. Each has their own requirements (Facebook requires SSL, most require a differently formatted manifest file, etc…), but the time it takes to get into each is typically less than 30 minutes. If you want to reduce that even more, Clay.io helps auto-generate the manifest files and promotional image assets you’ll need (as well as takes care of the SSL requirement) – documentation on that here.

Some marketplaces you’ll need to have a native wrapper for your game – primarily the iOS App Store and Google Play. A wrapper like PhoneGap is one option, but the native webviews have pretty terrible JavaScript engines, so for now you’re better off with tools like CocoonJS and Ejecta.

Now it’s up to you to go forth and make a great, innovative web game – I’m looking forward to see what’s on the horizon in the coming months and years!

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)