NY HTML5 - Game Development with HTML5 & JavaScript

104
GAME DEVELOPMENT Using HTML5 & JavaScript Rob Hawkes Hi, I’m Rob Hawkes and I’m here today to talk about creating games on the open Web using HTML5 and JavaScript.

description

In this talk I will bring you up to speed with using HTML5 tools and techniques for game development. I will discuss some basic and advanced techniques and highlight the key lessons that I've learnt, as well as the technologies and game engines that you should be aware of.

Transcript of NY HTML5 - Game Development with HTML5 & JavaScript

Page 1: NY HTML5 - Game Development with HTML5 & JavaScript

GAME DEVELOPMENT

Using HTML5 & JavaScript

Rob Hawkes

Hi, I’m Rob Hawkes and I’m here today to talk about creating games on the open Web using HTML5 and JavaScript.

Page 2: NY HTML5 - Game Development with HTML5 & JavaScript

I work at Mozilla, a non-profit fighting for a better Web. The guys who make Firefox.

Unsure about how much I like Mozilla? This here is a beautiful chicken and leek pie with extra Firefox goodness.

It was made by my talented girlfriend and it was delicious.

Page 3: NY HTML5 - Game Development with HTML5 & JavaScript

My official job title is Technical Evangelist, but I prefer what it says on my business card.

Part of my job is to engage with developers like you and I about cool new technologies on the Web.

And for those of you with no idea of what a rawket is, I made a multiplayer game called Rawkets in which players fly around in little rockets and shoot each other in the face with the latest Web technologies. It’s quite addictive!

http://rawkets.com

Page 4: NY HTML5 - Game Development with HTML5 & JavaScript

I’m not sure how much time we’ll have for questions at the end, but feel free to grab me in person after the talk or on Twitter.

These slides will go online after this talk.

I’ll put all the details up at the end.

Page 5: NY HTML5 - Game Development with HTML5 & JavaScript

Before we move on I just have a quick disclaimer.

This whole talk is about HTML5 and JavaScript as technologies for the creation of games.

They’re technologies that are intrinsically linked to each other by nature, but saying HTML5 and JavaScript every single time makes my head hurt.

So instead I’ll just be saying HTML5.

Just bear in mind that whenever I mention HTML5 I’m also referring to JavaScript as well.

Page 6: NY HTML5 - Game Development with HTML5 & JavaScript

So let’s go back in time for a moment.

Now I don’t actually remember when I first started playing computer games, although I know that I started with consoles.

Page 7: NY HTML5 - Game Development with HTML5 & JavaScript

My first experience was with the ZX Spectrum and its amazing noises and epic loading times, which I sorely miss…

Page 8: NY HTML5 - Game Development with HTML5 & JavaScript

Then there was the SNES, which really got me addicted to gaming.

Although it turns out my SNES was stolen when I was a kid. I did wonder where it went…

Page 9: NY HTML5 - Game Development with HTML5 & JavaScript

My parents replaced it with the Megadrive which, although not quite as awesome, was just as fun.

From there it has been a constant stream of consoles, each smashing the performance and functionality of its predecessor.

The N64, the Gamecube, the Dreamcast, the Playstation, the xBox.

You get the idea…

Page 10: NY HTML5 - Game Development with HTML5 & JavaScript

And spread throughout that time I dabbled in PC gaming, starting with games like Sim City…

Page 11: NY HTML5 - Game Development with HTML5 & JavaScript

And Megarace.

Who remembers this one?

Page 12: NY HTML5 - Game Development with HTML5 & JavaScript

And playing multiplayer Doom at my Dad’s Internet cafe.

What I’m getting at here is that gaming has been a big part of my life growing up, as it has been with a lot of other people as well.

They’re fun to play, and they’re surprisingly fun to make.

Page 13: NY HTML5 - Game Development with HTML5 & JavaScript

The time is now

Threshold of something cool

Today we’re now on the threshold of something cool; being able to create awesome and addictive games with nothing more than the technologies that we normally use to make websites, namely HTML5 and JavaScript.

Since I began developing on the Web I really can’t remember a time when so many people are working together to achieve something like this.

Page 14: NY HTML5 - Game Development with HTML5 & JavaScript

Notable events

Important goings-on in HTML5 gaming

Recently there have been some particularly notable events surrounding HTML5 gaming.

Page 15: NY HTML5 - Game Development with HTML5 & JavaScript

Acquisitions

HTML5 game engines being bought up

The acquisition of HTML5 gaming engines by large companies.

Like Aves being bought by Zynga and Rocket Engine bought by Disney.

Page 16: NY HTML5 - Game Development with HTML5 & JavaScript

Recruitment

HTML5 game developers are wanted

The recent recruitment of HTML5 games developers for well-known gaming companies, like Crytek.

http://crytek.com/career/offers/overview/frankfurt/programming-engineering/html5-game-dev

Page 17: NY HTML5 - Game Development with HTML5 & JavaScript

Funding

Investing in the pioneers

The huge amounts of funding being made available to games that help prove the Web as a gaming platform.

Like the Game Lab from Bocoup and Atari’s general sponsorship of HTML5 games.

http://gamelab.bocoup.com

Page 18: NY HTML5 - Game Development with HTML5 & JavaScript

Conferences

Discussing the future of HTML5 games

The two large-scale HTML5 gaming conferences last year; onGameStart in Poland and New Game in San Francisco. As well as a whole bunch of HTML5-related sessions at GDC this year.

Each attended by hundreds of game and Web developers alike.

Page 19: NY HTML5 - Game Development with HTML5 & JavaScript

Browser involvement

Providing the tech for HTML5 games

The investing of time and resources by Google, Mozilla and Opera into the creation of technologies and services for the benefit of gaming on the open Web.

Some of which we’ll be looking at in a moment.

Page 20: NY HTML5 - Game Development with HTML5 & JavaScript

Better tooling

Improving at a noticeable rate

Game engines and tooling for HTML5 development have been improving at a noticeable rate.

I’ll cover some of these game engines further on in the talk.

Page 21: NY HTML5 - Game Development with HTML5 & JavaScript

Porting hit iO

S games

Showing HTML5 is more than capable

And the recent port to HTML5 of massively successful iOS games like Angry Birds, Fieldrunners, and Cut The Rope.

http://chrome.angrybirds.comhttp://fieldrunnershtml5.appspot.comhttp://www.cuttherope.ie

Page 22: NY HTML5 - Game Development with HTML5 & JavaScript

Existing games

Some of the best examples

The number of HTML5 games out there is growing every day.

In any case I thought I’d show you a selection of my favourites, just a tiny amount of what’s out there.

Page 23: NY HTML5 - Game Development with HTML5 & JavaScript

Quake II

Multiplayer Quake II remake with Google GWT (Google Web Toolkit).

http://code.google.com/p/quake2-gwt-port/

Page 24: NY HTML5 - Game Development with HTML5 & JavaScript

Angry Birds

There isn’t much to say about Angry Birds really, most of you probably know about it.

The HTML5 version uses WebGL for accelerated 2D graphics.

Page 25: NY HTML5 - Game Development with HTML5 & JavaScript

Fieldrunners

Fieldrunners was ported from iOS to HTML5 by Bocoup.

Like Angry Birds, it also uses WebGL for accelerated 2D graphics.

Page 26: NY HTML5 - Game Development with HTML5 & JavaScript

Cut The Rope

Cut The Rope was also ported from iOS to HTML5.

Page 27: NY HTML5 - Game Development with HTML5 & JavaScript

Bejeweled

Bejeweled is a massively popular game on a whole variety of platforms.

Popcap recently released a purely HTML5 version that uses WebGL for accelerated 2D graphics.

Page 28: NY HTML5 - Game Development with HTML5 & JavaScript

Command & Conquer

Command & Conquer: Tiberium Alliances is a HTML5 game from EA that uses canvas for the graphics.

Page 29: NY HTML5 - Game Development with HTML5 & JavaScript

GT Racing

GT Racing: Motor Academy by Gameloft and Mandreel. Using WebGL for accelerated 3D graphics.

http://www.mandreel.com/?page_id=1312

Page 30: NY HTML5 - Game Development with HTML5 & JavaScript

BrowserQuest

BrowserQuest is a massively-multiplayer RPG that Mozilla recently launched to the public.

It was created by Little Workshop in France and uses HTML5 canvas for the graphics, WebSockets for real-time communication, and a whole range of other tech to handle save-game data and other things.

It works great on mobile and desktop devices but what’s even better is that, aside from being an addictive game, the entire source code is on GitHub.

http://browserquest.mozilla.orghttps://github.com/mozilla/BrowserQuesthttp://hacks.mozilla.org/2012/03/browserquest/

Page 31: NY HTML5 - Game Development with HTML5 & JavaScript

It’s clear that HTML5 is something that is really becoming a contender for games on the Web.

It’s an open technology stack that is pluginless, doesn’t require compilation, and works the same across devices and platforms.

Page 32: NY HTML5 - Game Development with HTML5 & JavaScript

But just because HTML5 is the trendy thing doesn’t mean that you need to use it.

So why might you not want to use it?

Page 33: NY HTML5 - Game Development with HTML5 & JavaScript

Full compatibility

Some thing aren’t supported everywhere

Not every browser supports every part of HTML5.

For example, canvas isn’t supported out of the box by any IE below 9. Although, you can use ExplorerCanvas to replicate canvas functionality, but it’s not ideal and as doesn’t perform as well.

WebSockets is only support in IE10 and has poor support on Android. But again, you can fake this by using Flash for the sockets, like with Socket.IO.

WebGL also has patchy support with absolutely no support in IE, and Safari and Opera requiring a development build.

There is no denying that the cross-browser situation is by no means perfect for some functionality.

Page 34: NY HTML5 - Game Development with HTML5 & JavaScript

No DRM

It goes against th

ese technologies

If you need DRM or have a burning desire to hide absolutely everything about your code.

Remember, the code isn’t compiled, so where would the DRM go? The beauty of Web technologies is that they can be read as plain text by simply viewing the page source.

However, DRM isn't bulletproof in itself and you can still crack into things like Flash.

You can obfuscate and minify your code if you think it will help, but even this can be worked around with relative ease.

Page 35: NY HTML5 - Game Development with HTML5 & JavaScript

Technology limitations

HTML5 never promised to do everything

It is wrong to see HTML5 as a one-size-fits-all solution.

There are things that it’s meant to do, and things that it’s not meant to do.

Comparing HTML5 to other technologies always results in, “but HTML5 doesn’t to this, or that.”

In cases like that, perhaps HTML5 isn’t the right technology for you.

Page 36: NY HTML5 - Game Development with HTML5 & JavaScript

Technology

Behind the scenes of HTML5 games

There are a few key technologies that are involved in the development of HTML5 games.

Here are some of my favourites.

Page 37: NY HTML5 - Game Development with HTML5 & JavaScript

Canvas

2D graphics platform

Canvas is a 2D graphics platform that uses both HTML5 and JavaScript.

It’s quite amazing what can be done with such simple drawing and image manipulation tools.

https://developer.mozilla.org/en/HTML/Canvas

Page 38: NY HTML5 - Game Development with HTML5 & JavaScript

Silk is a stunning example of what can be achieved by combining the simple drawing tools available in canvas.

http://weavesilk.com

Page 39: NY HTML5 - Game Development with HTML5 & JavaScript

WebGL

3D graphics platform

WebGL brings the ability to provide advanced 3D graphics directly within the browser.

https://developer.mozilla.org/en/WebGL

Page 40: NY HTML5 - Game Development with HTML5 & JavaScript

HelloRacer is a little game that lets you drive a Formula One car around your browser. It’s a beautiful example of WebGL in action.

http://helloracer.com/webgl/

Page 41: NY HTML5 - Game Development with HTML5 & JavaScript

Rome is a music video created with WebGL. It’s an amazing example of what the technology can achieve in a real-world situation given a large team.

http://ro.me

Page 42: NY HTML5 - Game Development with HTML5 & JavaScript

This is a rather freaky example of how interesting WebGL is.

It’s a demo that shows just how realistic WebGL can render materials, like skin. This isn’t much unlike the quality of modern games consoles!

http://www.everyday3d.com/j3d/demo/014_Head.html

Page 43: NY HTML5 - Game Development with HTML5 & JavaScript

requestAnimationFrame

Optimised animation loops

requestAnimationFrame is the new, better way of managing animation in JavaScript.

Instead of constantly running a setTimeout or setInterval function, which lack performance and spike CPU usage, requestAnimation frame puts the browser in control of things and keeps things running smoothly.

Page 44: NY HTML5 - Game Development with HTML5 & JavaScript

HTML5 audio

Sound effects and background music

HTML5 audio allows for plugin-less game sound effects and background music.

Audio data APIs implemented by Mozilla and Google allow for manipulation of audio and much more fine-grained control.

https://developer.mozilla.org/en/HTML/Element/audio

Page 45: NY HTML5 - Game Development with HTML5 & JavaScript

This is something I made especially for the ASSEMBLY 2011 event in Finland.

It’s an audio visualiser that uses WebGL and the HTML5 Audio Data API.

http://robhawkes.github.com/webgl-html5-audio-visualiser/

Page 46: NY HTML5 - Game Development with HTML5 & JavaScript

WebSockets

Multiplayer communication

WebSockets can be used for the real-time communication between a player and the game server.

With WebSockets you can create multiplayer games with relative ease.

https://developer.mozilla.org/en/WebSockets

Page 47: NY HTML5 - Game Development with HTML5 & JavaScript

Local storage

Storing data on the player device

Methods like the application cache, Local Storage, and IndexedDB are great for storing data locally on the player device.

This way you can cache game data and allow the game to pick up where the player left off.

https://developer.mozilla.org/en/DOM/Storagehttps://developer.mozilla.org/en/Offline_resources_in_Firefoxhttps://developer.mozilla.org/en/IndexedDB

Page 48: NY HTML5 - Game Development with HTML5 & JavaScript

Web Workers

Multi-threaded JavaScript

Web Workers allow you to run JavaScript in separate background threads.

This allows you to offload computationally-heavy tasks with a single worker, or tackle large quantities of data in a fraction of the time by spreading tasks over multiple workers.

https://developer.mozilla.org/En/Using_web_workers

Page 49: NY HTML5 - Game Development with HTML5 & JavaScript

Full Screen API

Simple, yet powerful

The Full Screen API allows you to expand any HTML element to fill the users screen, even if the browser isn’t running full screen itself.

The Mozilla implementation is not perfect yet because you can’t use the whole keyboard in full-screen mode without a message popping up, but it’s in the latest Nightly builds and works in all other respects.

https://bugzilla.mozilla.org/show_bug.cgi?id=545812http://blog.pearce.org.nz/2011/09/mozilla-full-screen-api-progress-update.htmlhttps://wiki.mozilla.org/Platform/Features/Full_Screen_APIs

Page 50: NY HTML5 - Game Development with HTML5 & JavaScript

Pointer Lock API

Locking the cursor in one place

The Pointer Lock API is an attempt at improving the mouse as an input device.

It would be used in situations like games and 3D visualisations where the mouse position rotates or moves you around a 3D space.

As it stands there’d still be a cursor moving around the screen causing all sorts of trouble when you want to click on something in your game.

With the new API you can lock your mouse position and stop it from getting in the way and being a nuisance.

Both Google and Mozilla are working on an implementation of this right now, it’s available in a custom build of Firefox.

https://developer.mozilla.org/en/API/Pointer_Lock_APIhttps://bugzilla.mozilla.org/show_bug.cgi?id=633602

Page 51: NY HTML5 - Game Development with HTML5 & JavaScript

Gamepad API

Bringing the console to the Web

The Gamepad API is one of the major improvements to input that is coming.

Both Mozilla and Google are working an an implementation of this and there is actually an experimental build of Firefox available to the public that has it working. The API is also in the dev build of Chrome.

What I find most interesting about the Gamepad API is that it might be just the thing we need to finally justify HTML5 gaming on a TV or console.

Who wants to use a keyboard and mouse while sitting on the sofa?

https://wiki.mozilla.org/GamepadAPIhttp://www.gamepadjs.comhttps://github.com/jbuck/input.js

Page 52: NY HTML5 - Game Development with HTML5 & JavaScript

Gamepad API demo

I’d like to show you a quick demo of the Gamepad API working in Firefox Nightly and Google Chrome.

In this example I’ve connected my Logitech controller to my Mac, but I could also use a PS3 controller or practically any other USB controller.

Page 53: NY HTML5 - Game Development with HTML5 & JavaScript

This is another little demo that I put together to show off the Gamepad API implemented in my game Rawkets.

Page 54: NY HTML5 - Game Development with HTML5 & JavaScript

Web applications

Not just a fancy website

The concept of Web apps is something that is gaining a lot of traction at the moment.

HTML5 games are effectively glorified Web apps.

It’s no doubt this this traction is as a result of the success of native applications and games on the desktop and mobile, particularly with iOS and Android.

Page 55: NY HTML5 - Game Development with HTML5 & JavaScript

App-like experience

Launch from the desktop or home screen

Something that needs to be tackled with Web apps is how to make them feel like real applications rather than glorified websites.

One way that is being considered is completely removing the browser chrome and running the application in it’s own window.

This will effectively mean that you have full control of the app UI and it won’t look like it’s being run in a browser.

Page 56: NY HTML5 - Game Development with HTML5 & JavaScript

At Mozilla we call this WebRT, which stands for Web Run-Time.

By using WebRT you can install a Web app directly into the OS just like you would a native application.

The WebRT app will look and feel like a native application when launched but will actually be running a browser rendering engine behind the scenes.

This is an example of Rawkets running as a WebRT app with the Firefox rendering engine. Notice the lack of browser UI.

Page 57: NY HTML5 - Game Development with HTML5 & JavaScript

Node.js

Game logic and network communication

Node is often used as a multiplayer game server, controlling the logic and handling the WebSockets connections to the players.

It can be used for player authentication and the storage of data so gameplay can persist over multiple game sessions.

This is all made relatively easy with great third-party modules, like Socket.IO for WebSockets, and others that handle Redis and MongoDB for storage, for example.

http://nodejs.org

Page 58: NY HTML5 - Game Development with HTML5 & JavaScript

Game engines

Create HTML5 games today

If you haven’t already then I encourage you to give HTML5 game development a go.

And you don't have to create an entire game infrastructure from scratch, you can use some of the existing engines that are proving popular.

Page 59: NY HTML5 - Game Development with HTML5 & JavaScript

Impact. A 2D game engine.

I used this recently, and it’s really well made and has a good level editor and development tools.

The documentation is great and the author is active and very helpful.

http://impactjs.com/

Page 60: NY HTML5 - Game Development with HTML5 & JavaScript

Crafty. Another 2D game engine.

It’s a free engine and is doing much better than other free engines out there.

http://craftyjs.com/

Page 61: NY HTML5 - Game Development with HTML5 & JavaScript

Isongenic Engine. A 2D to 2.5D game engine.

One of the most promising engines out there today.

Massively multiplayer networking built in, uses Node and MongoDB, and has canvas or DOM-based graphics.

http://www.isogenicengine.com

Page 62: NY HTML5 - Game Development with HTML5 & JavaScript

Conversion & porting

Using a single code-base

A lot of game developers want to target browsers but don’t want to rewrite their existing games in JavaScript.

To help this process, various methods of converting an existing code-base to JavaScript are starting to appear.

Page 63: NY HTML5 - Game Development with HTML5 & JavaScript

Emscripten

https://github.com/kripken/emscripten/wiki

Page 64: NY HTML5 - Game Development with HTML5 & JavaScript

Mandreel

http://www.mandreel.com

Page 65: NY HTML5 - Game Development with HTML5 & JavaScript

PlayN

https://developers.google.com/playn/

Page 66: NY HTML5 - Game Development with HTML5 & JavaScript

PhoneGap

http://phonegap.com

Page 67: NY HTML5 - Game Development with HTML5 & JavaScript

CocoonJS

http://www.ludei.com

Page 68: NY HTML5 - Game Development with HTML5 & JavaScript

Distribution and payment

Finding an audience and making money

Making games is only half the battle.

Once you have a game finished how to you promote it and get it in front of players?

And even more important, how do you earn money from it?

Page 69: NY HTML5 - Game Development with HTML5 & JavaScript

Mozilla Marketplace

We envisage Web apps to run on any device, any browser, and to be distributed through any store or website.

Right now the payment provider is PayPal, though you can set up your own store using our APIs and use any provider you want.

https://apps.mozillalabs.comhttps://developer.mozilla.org/en/OpenWebAppshttps://marketplace.mozilla.org

Page 70: NY HTML5 - Game Development with HTML5 & JavaScript

Chrome Web Store.

Uses Google Checkout for payment.

https://chrome.google.com/webstore

Page 71: NY HTML5 - Game Development with HTML5 & JavaScript

Facebook

Uses Facebook Credits for payment.

https://developers.facebook.com

Page 72: NY HTML5 - Game Development with HTML5 & JavaScript

iOS App Store

By using services like PhoneGap and CocoonJS you can package your game up and sell it on the iOS App Store, just like any other native application.

Uses the iTunes store for payments.

https://developer.apple.com

Page 73: NY HTML5 - Game Development with HTML5 & JavaScript

Issues

Making games can be a challenge

It’s not all plain sailing when making a gaming using HTML5 and JavaScript.

I’m going to cover a few of the main issues that tripped me up during the development of Rawkets.

Page 74: NY HTML5 - Game Development with HTML5 & JavaScript

Tweaking animation

Putting the browser in

control

One of the simplest fixes is to stop using setTimeout or setInterval and to use requestAnimationFrame instead.

If you use setTimeout or setInterval and don’t manage it then you put a huge amount of stress on the CPU and continue that stress even if you switch tabs or minimise the browser.

By using requestAnimationFrame you give the browser control over when a new animation loop should occur, reducing load on the CPU and saving battery life on mobile devices.

requestAnimationFrame also automatically limits the number of updates if you switch to another tab or minimise the browser, again saving resources and keeping your players happy.

Right now you can’t easily set a specific framerate when using requestAnimationFrame but so long as you use time-based updates (not frame-based) in your game then you’ll be fine.

Page 75: NY HTML5 - Game Development with HTML5 & JavaScript

Networking

Not as easy as I thought

Issues with networking have plagued development of the game right from the beginning.

This probably stems from my lack of prior experience with socket connection and multiplayer gaming in general.

In the original prototype of the game the network communication was woefully simple and everything was transmitted in a verbose format with no further thought.

In hindsight it’s obvious why I was experiencing massive performance issues with the network communication. I was basically sending way too much data back and forth.

Page 76: NY HTML5 - Game Development with HTML5 & JavaScript

Message protocol

Structured and short communication

One of the ways that I solved these problems was by implementing a structured protocol for the messages that are being sent and received.

This included assigning each message type a number and using enumeration to represent those types in the code.

Page 77: NY HTML5 - Game Development with HTML5 & JavaScript

types = {

PING: 1,

SYNC: 2,

SYNC_COMPLETED: 3,

NEW_PLAYER: 4,

UPDATE_PLAYER: 5,

UPDATE_INPUT: 6,

REMOVE_PLAYER: 7

};

Enumeration

By enumerating the messages types like this I was able to refer to them in a verbose format within the code, but benefit from only sending the one or two digit number when transmitting a message.

This is only possible if both the client and server follow the same protocol in regards to which number refers to which message type.

It’s a simple but effective solution and allowed me to cut a large number of characters from transmitted messages.

Page 78: NY HTML5 - Game Development with HTML5 & JavaScript

1 | 1234567890 | 1316763202872 | 5 | 34

Message package

MSG_ID PLAYER_ID TIMESTAMP X Y

Put together with the message types, a full message package is put together as a simple string representation of a JavaScript object.

All the other pieces of data are attached to the object with a key that is as short as possible.

The MSG_ID that you can see above is a reserved key that is used solely for the message type.

The other items in this example are the player id, timestamp, and the player position.

Page 79: NY HTML5 - Game Development with HTML5 & JavaScript

Compression

Reducing data as much as possible

Data in WebSockets is normally transmitted as verbose plain text, so it’s important to cut down and compress it as much as possible.

Some of the ways that I’ve done this include rounding numerical values, reducing the length of words if they’re only used for reference, and generally removing any data that isn’t necessary.

Page 80: NY HTML5 - Game Development with HTML5 & JavaScript

Binary messages

Even shorter, faster communication

I never got around to implementing this but there is now binary message support in WebSockets.

By switching to binary you can reduce the size of your messages by a noticeable amount while also increasing the amount of data that you can transmit at a single point in time.

http://hobbycoding.posterous.com/websockt-binary-data-transfer-benchmark-rsulthttp://hobbycoding.posterous.com/the-fastest-websocket-module-for-nodejs

Page 81: NY HTML5 - Game Development with HTML5 & JavaScript

Rate limitin

g

Cutting down on communication

Aside from the message protocol, one of the biggest issues with networking has been dealing with the sheer number of messages being sent back and forth during the lifetime of a game.

Page 82: NY HTML5 - Game Development with HTML5 & JavaScript

1 1

MESSAGES IN

1MESSAGES OUT

1

Having only one player in the game is easy, you have one message coming in to the server, saying the player has moved, for example, and one message coming back out, updating the player with details from the server.

Page 83: NY HTML5 - Game Development with HTML5 & JavaScript

1 2

2 1

MESSAGES IN

2MESSAGES OUT

4

So say we now have two players, there is still only 1 message in from each player, but now each player receives 2 messages back from the server; one for them, and one for the other player.

This isn’t too bad, but notice how the server is having to send 4 messages – 2 for each player.

Page 84: NY HTML5 - Game Development with HTML5 & JavaScript

1 4

4 1

1

4

4

1

MESSAGES IN

4MESSAGES OUT

16

4 players now, look how the server is having to send 16 messages, yet it only receives 4.

If you haven’t already noticed, the messages out from the server are the square of the number of players.

But 16 messages out is alright, it’s hardly going to tax the server.

Page 85: NY HTML5 - Game Development with HTML5 & JavaScript

MESSAGES IN

30MESSAGES OUT

9001 30

30 1

1

30

30

1

So imagine if we now move into properly multiplayer territory.

30 players in the game would mean 30 messages coming in to the server, and 900 – NINE HUNDRED – messages going out, every update. That’s a silly amount of data for just 30 people.

But let’s go further still…

Page 86: NY HTML5 - Game Development with HTML5 & JavaScript

MESSAGES IN

100MESSAGES OUT

100001 100

100 1

1

100

100

1

Say we go massively multiplayer and have 100 players in the game at one time.

It’s not so bad for each individual player, they send one message in and get 100 back – that’s bearable.

But check out the server, it’s getting 100 messages in and is having to send out 10,000 back, every update. That’s just a mentally stupid number that’s going to cause a lot of grief.

Page 87: NY HTML5 - Game Development with HTML5 & JavaScript

Intelligence

Letting the game prioritis

e messages

Fortunately there is a way around this that cuts down the amount of messages sent; you just need to send data only for players visible to another player, in essence filtering out game data that doesn't affect the current player.

Another trick I used is to only send updates when a player is active and moving. If they haven’t moved since the last frame and nothing else has changed then why bother sending an update and wasting bandwidth?

These are such simple solutions, but ones that I never even considered at first.

Page 88: NY HTML5 - Game Development with HTML5 & JavaScript

Respecting TCP

WebSockets uses TCP. Deal with it

Something else that I discovered is important to be aware of when making a game with WebSockets is that you’re using TCP.

This is a problem as such, but it means that you need to play by a certain set of rules, and to expect a certain set of issues.

By the way, I should point out that that you could argue that the icon that I’ve used could represent WebSockets, but that’s not why I used it. It’s the US plug symbol and I just thought it was funny because it looks like a surprised face. The UK plug symbol is boring in comparison.

Page 89: NY HTML5 - Game Development with HTML5 & JavaScript

Obey the order

You can’t do much about it

One issue with TCP is that packets will come through in order and get queued up if there are any significant connection issues.

This can be a problem with a real-time game as it can cause hang-ups in the transmission and subsequently a hang-up in the graphic display.

In short, the ordering issue can result in jumpy gameplay. Not fun.

With UDP this wouldn’t be so much of a problem, but we don’t have that luxury yet. Although similar protocols are in the pipeline and may make their way into our lives relatively soon, things like Media Streaming APIs and WebRTC.

Page 90: NY HTML5 - Game Development with HTML5 & JavaScript

Cheaters

A blessing and a curse

There’s no denying it, your code is going to be visible to anyone who wants to look at the source.

I experienced this early on in the development of the game with players adding in their own features, like invincibility, epic speed, rapid-fire, and even creating completely new weapons like cluster bombs!

Now don’t get me wrong, I actually appreciate the cheaters because they highlighted all the errors of my ways, for free. One of the benefits of the open nature of JavaScript is that it can be looked at and poked very easily by others, which means that I can fix bugs quicker than if I was testing on my own.

Page 91: NY HTML5 - Game Development with HTML5 & JavaScript

Globals are bad

Don’y keep code wide open

There are two reasons why cheating was so prevalent and so easy to do.

The first is that by keeping all the game code in the global namespace and not using anything like closures I was practically inviting people to come in and edit the game code. It was too easy to do!

It was so easy in fact that after a few hours of releasing the first prototype, players were already sharing code snippets that others could paste into their browser console to get new features. Annoying, but actually pretty cool.

Page 92: NY HTML5 - Game Development with HTML5 & JavaScript

Client authority

Power isn’t always a good thing

I’m not going to lie, the first version of Rawkets was way too trusting.

I used what is referred to as the authoritative client model, which basically means that the client, the player, made all the decisions regarding its position and then sent those positions to the server.

The server than trusted those positions and transmitted them to all the other players, which is fine until the client edits their position and increments it by 100 pixel per frame, rather than 5. Bad times.

This can be referred to as the “Here I am” approach.

Page 93: NY HTML5 - Game Development with HTML5 & JavaScript

Server authority

Relinquish that power

The solution is to make the server authoritative, which means that you prevent manipulation of the client’s code from doing any damage.

All the movement logic is now performed on the server, meaning that when a client moves it simply lets the server know which direction it wants to move. From there the server calculates the new position and sends it back to the client.

This can be referred to as the “Where am I?” approach, and if done right it can completely remove the ability to cheat.

Page 94: NY HTML5 - Game Development with HTML5 & JavaScript

Client Server Client+0 +40 +80

40ms 40ms

80ms total round-trip

Inherent latency

However, the problem with the authoritative server model is that there is some inherent latency within the system.

What I mean by this is that it obviously takes some time for a movement to be sent from the client to the server, then for the server to move the client, and then for the server to send the new position back again.

In the example here imagine that there is a 40ms latency between the client and server, which means that a message sent to the server will take a total of 80ms to make the round-trip.

The problem here is what happens during that 80ms period that you’re waiting for the updated position? If you do nothing then there’s going to be an 80ms delay between you pressing the up arrow and your rawket moving forward. Not good.

Page 95: NY HTML5 - Game Development with HTML5 & JavaScript

Client prediction

Server authority isn’t enough

To solve the latency issues with the authoritative server you need to implement some element of prediction on the client.

What I mean by prediction is an ability for the client to guess, quite accurately, where it should move the player before the message comes back from the server detailing the new position.

Page 96: NY HTML5 - Game Development with HTML5 & JavaScript

Prediction happens here

Client Server Client+0 +40 +80

40ms 40ms

Instant movement

The prediction happens as soon as the client performs some sort of movement (a key-press, etc), before the server has received the input.

All the prediction does is run the same physics as the server, based on the new input.

This is exactly as if were using the authoritative client model, apart from one important difference.

Page 97: NY HTML5 - Game Development with HTML5 & JavaScript

Correction

When prediction goes wrong

Whereas the authoritative client model would be in control, with the authoritative server model and client prediction, the server is in control.

The whole point of using the authoritative server is because the client can’t be trusted. So it makes sense that prediction can’t be trusted either.

To get around this you use periodically check the client position against the server and perform a correction if necessary.

This may sound simple in concept, but it’s one of the hardest aspect of multiplayer gaming to get right. Simply because it’s obvious when you get it wrong.

Page 98: NY HTML5 - Game Development with HTML5 & JavaScript

Stability

Keeping the game running

Keeping the game running is massively important, especially while it’s in rapid development and is prone to crashing (through errors of my own I must add).

I needed a way to automatically restart the game server if it crashed or something went horribly wrong.

I also needed a way to scale the game and keep it running as fast as possible.

Page 99: NY HTML5 - Game Development with HTML5 & JavaScript

Forever

I use a little Node module called Forever. It’s amazing!

https://github.com/nodejitsu/forever

Page 100: NY HTML5 - Game Development with HTML5 & JavaScript

forever start game.js

Forever

All I have to do now is make sure the game process quits on a catastrophic error and Forever will automatically restart it for me.

Using Forever is as simple as installing the module with NPM and then starting your Node script using the Forever demon. The rest is taken care of for you.

Page 101: NY HTML5 - Game Development with HTML5 & JavaScript

Hook.io

Some of you may also be interested in hook.io, which can help create more stable Node applications.

The concept is to decouple your application logic by breaking it into individual processes so that if one process goes down the rest can continue to run and your entire game doesn’t crash.

You use hook.io through its event system that lets you communicate between these separate processes, regardless of whether they’re on the same server or not. It’s a pretty cool concept.

https://github.com/hookio/hook.io

Page 102: NY HTML5 - Game Development with HTML5 & JavaScript

Become a canvas master

RAWKES.COM/FOUNDATIONCANVAS

Out now

Paperback and digital formats

Learn how to animate

Make two cool space games

Foundation HTML5 Canvas

Foundation HTML5 Canvas is out now on Amazon and other reputable book stores.

http://rawkes.com/foundationcanvas

Page 103: NY HTML5 - Game Development with HTML5 & JavaScript

Rob Hawkes

Rawkets.comHTML5 & WebSockets game

Twitter sentiment analysisDelving into your soul

RECENT PROJECTS

Rawkes.comPersonal website and blog

MORE COOL STUFF

Rawket ScientistTechnical Evangelist at Mozilla

@robhawkes

Get in touch with me on Twitter: @robhawkes

Follow my blog (Rawkes) to keep up to date with stuff that I’m working on: http://rawkes.com

I’ve recently worked on a project that analyses sentiment on Twitter: http://rawkes.com/blog/2011/05/05/people-love-a-good-smooch-on-a-balcony

Rawkets is my multiplayer HTML5 and JavaScript game. Play it, it’s fun: http://rawkets.com

Page 104: NY HTML5 - Game Development with HTML5 & JavaScript

THANK YOU

Question? Grab me later

Rob Hawkes

@robhawkes

Thank you.

If you have any questions feel free to grab me here, on Twitter (@robhawkes)