MDN Hackday London - Open Web Games with HTML5 & JavaScript

66
OPEN WEB GAMES 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 give you an overview of the new role that browsers are adopting to support games and the technologies and processes that are helping that happen. This includes areas like 2D graphics with canvas, console-like 3D games with WebGL, gamepad support, immersive full-screen experiences, multiplayer games with WebSockets, and much more.

Transcript of MDN Hackday London - Open Web Games with HTML5 & JavaScript

Page 1: MDN Hackday London - Open Web Games with HTML5 & JavaScript

OPEN WEB GAMES

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: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games 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 4: MDN Hackday London - Open Web Games 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 5: MDN Hackday London - Open Web Games 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 6: MDN Hackday London - Open Web Games with HTML5 & JavaScript

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

Page 7: MDN Hackday London - Open Web Games 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 8: MDN Hackday London - Open Web Games 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 9: MDN Hackday London - Open Web Games with HTML5 & JavaScript

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

Page 10: MDN Hackday London - Open Web Games with HTML5 & JavaScript

And Megarace.

Who remembers this one?

Page 11: MDN Hackday London - Open Web Games 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 12: MDN Hackday London - Open Web Games 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 13: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Existing games

Some of the best examples

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

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

Page 14: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Quake II

Fully-functional multiplayer Quake II port.

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

Page 15: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Cut The Rope

Cut The Rope, ported from iOS.

http://www.cuttherope.ie

Page 16: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Bejeweled

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

Popcap recently released a purely HTML5 version.

http://bejeweled.popcap.com/html5

Page 17: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Command & Conquer

Command & Conquer: Tiberium Alliances is a HTML5 game from EA that is part real-time strategy, part Farmville.

http://alliances.commandandconquer.com

Page 18: MDN Hackday London - Open Web Games with HTML5 & JavaScript

GT Racing

GT Racing: Motor Academy is a 3D racing game by Gameloft and Mandreel.

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

Page 19: MDN Hackday London - Open Web Games with HTML5 & JavaScript

BrowserQuest

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

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 20: MDN Hackday London - Open Web Games 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 plugin-less, doesn’t require compilation, and works the same across devices and platforms.

Page 21: MDN Hackday London - Open Web Games 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 22: MDN Hackday London - Open Web Games 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 23: MDN Hackday London - Open Web Games 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 24: MDN Hackday London - Open Web Games with HTML5 & JavaScript

<canvas id='myCanvasElement' width='400' height='400'></canvas>

Canvas

Using canvas is very straight forward.

The first thing you need to do is add a canvas DOM element to your HTML page.

Page 25: MDN Hackday London - Open Web Games with HTML5 & JavaScript

var canvas = document.getElementById('myCanvasElement');  

var ctx = canvas.getContext('2d');

ctx.fillStyle = "rgb(200,0,0)";  

ctx.fillRect(10, 10, 55, 50);  

  

ctx.fillStyle = "rgba(0, 0, 200, 0.5)";  

ctx.fillRect(30, 30, 55, 50);

Canvas

From there you can then access the canvas through JavaScript to draw on it and do other cool stuff.

This is small canvas demo that draws a solid red square underneath a blue one with half transparency.

‘myCanvasElement’ refers to a HTML <canvas> element that you’ll need to place in your HTML file somewhere. In this example, I’m assuming that you’ve already done that.

Page 26: MDN Hackday London - Open Web Games 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 27: MDN Hackday London - Open Web Games 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 28: MDN Hackday London - Open Web Games 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 29: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Tinkercad is probably the best use of WebGL that I’ve seen in a production situation.

It’s a Web app that allows you to create 3D objects in your browser using WebGL, then get them printed and sent to your doorstep in just a few simple clicks. It’s seriously awesome.

https://tinkercad.com

Page 30: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Both Google Maps and Nokia have recently added support for WebGL. The Nokia version is particularly impressive because they fully render and texture 3D shapes of buildings.

http://support.google.com/maps/bin/answer.py?hl=en&answer=1630790http://maps.nokia.com/webgl/

Page 31: MDN Hackday London - Open Web Games with HTML5 & JavaScript

I’m not going to lie, WebGL isn’t the easiest thing to learn. Then again, no raw 3D code is that simple.

Instead, I recommend checking out a library called three.js which abstracts WebGL and makes it much easier to implement.

https://github.com/mrdoob/three.js/

Page 32: MDN Hackday London - Open Web Games 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.

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 33: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function update(timestamp) {  

// DO SOMETHING

  window.mozRequestAnimationFrame(update);  

}

 

window.mozRequestAnimationFrame(update);

requestAnimationFrame

In this example, I’m only using the Mozilla prefixed version of requestAnimationFrame. In reality, there’s a really good shim by Paul Irish that handles cross-browser requestAnimationFrame.

http://paulirish.com/2011/requestanimationframe-for-smart-animating/

Page 34: MDN Hackday London - Open Web Games 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 35: MDN Hackday London - Open Web Games 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 36: MDN Hackday London - Open Web Games with HTML5 & JavaScript

<audio id='myAudioElement' controls>

  <source src='audiofile.ogg' type='audio/ogg'>

</audio>

Audio

Like canvas, using audio is also straight forward.

The first thing you need to do is add an audio DOM element to your HTML page.

Page 37: MDN Hackday London - Open Web Games with HTML5 & JavaScript

var audio = document.getElementById('myAudioElement');

audio.play();

audio.pause();

Audio

From there you can then access the audio element through JavaScript to control it.

Page 38: MDN Hackday London - Open Web Games 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 39: MDN Hackday London - Open Web Games with HTML5 & JavaScript

var ws = new WebSocket('http://example.com/socketserver');

ws.send('This message is sent to the WebSocket server');

ws.onmessage = function (event) {  

  console.log(event.data);  

}

WebSockets

WebSockets are created entirely from JavaScript without the need to add elements to the HTML page.

A new WebSocket connection can be opened by calling the ‘new WebSocket’ constructor and passing it the URL to the WebSocket server.

From there you can call the ‘send’ method to push data to the server.

Or listen for the ‘onmessage’ event to handle data pushed to you from the server.

Page 40: MDN Hackday London - Open Web Games 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.

For games, this is great because you can make the small canvas element fill the entire screen.

Outside of games, this is useful for video elements and Web applications.

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 41: MDN Hackday London - Open Web Games with HTML5 & JavaScript

var canvas = document.getElementById('myCanvasElement');

canvas.mozRequestFullScreen();

Full Screen API

The Full Screen API can be requested from any DOM element.

In this example you’re asking a canvas element to expand to fill the screen.

One thing to note is that you can’t just make any element fill the screen whenever you want. Right now, the user has to click or press a key to initiate the Full Screen API.

Page 42: MDN Hackday London - Open Web Games 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 43: MDN Hackday London - Open Web Games with HTML5 & JavaScript

var canvas = document.getElementById('myCanvasElement');

canvas.mozRequestPointerLock();

Full Screen API

The Pointer Lock API can be requested from any DOM element that is already in full screen.

Page 44: MDN Hackday London - Open Web Games 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 45: MDN Hackday London - Open Web Games 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 46: MDN Hackday London - Open Web Games with HTML5 & JavaScript

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

Page 47: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function onGamepadConnected(e) {

var controller = e.gamepad;

console.log("Gamepad connected", controller.id);

}

window.addEventListener("MozGamepadConnected",

onGamepadConnected);

Connection

MozGamepadConnected

It passes an event object that itself contains a gamepad object in reference to the connected gamepad.

Page 48: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function onGamepadDisconnected(e) {

var controller = e.gamepad;

console.log("Gamepad disconnected", controller.id);

}

window.addEventListener("MozGamepadDisconnected",

onGamepadDisconnected);

Disconnection

MozGamepadDisconnected

It passes an event object that itself contains a gamepad object in reference to the disconnected gamepad.

Page 49: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function onGamepadButtonDown(e) {

var button = e.button;

console.log("Gamepad button pressed", button);

}

function onGamepadButtonUp(e) {

var button = e.button;

console.log("Gamepad button released", button);

}

window.addEventListener("MozGamepadButtonDown", onGamepadButtonDown);

window.addEventListener("MozGamepadButtonUp", onGamepadButtonUp);

Button events

MozGamepadButtonDownMozGamepadButtonUp

Each pass an event object that contains a button property.

The button property is the index number of the specific button, respective to the entire array of buttons on the gamepad.

Page 50: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function onGamepadAxisMove(e) {

var axis = e.axis;

var value = e.value;

console.log("Gamepad axis move", axis, value);

}

window.addEventListener("MozGamepadAxisMove", onGamepadAxisMove);

Axis events

MozGamepadAxisMove is fired on movement of a joystick or analogue trigger.

Passes an event object that contains axis and value properties.

The axis property is the index number of the specific axis that was moved, respective to the entire array of axes on the gamepad.

The value property is a -1.0 to 1.0 float. For example, an x-axis on a joystick when fully pressed to the left would have a -1.0 value.

Page 51: MDN Hackday London - Open Web Games with HTML5 & JavaScript

function checkState() {

for (var i = 0; i < controller.buttons.length; i++) {

console.log("Button state", i, controller.buttons[i]);

}

for (var j = 0; j < controller.axes.length; j++) {

console.log("Axis state", j, controller.axes[j]);

}

}

Gamepad state

If you don’t want to use events you can also poll the entire gamepad state whenever you want.

The only pre-requisite is that a gamepad is already connected and you’ve stored a reference to it somewhere, perhaps in a variable or array.

Once you have reference to a gamepad you get the state by reading its buttons and axes objects. These are both arrays that contain data about every single button and axis available.

The value of each button in the buttons array is a boolean that tells you whether the button is pressed down (true) or not (false).

The value of each axis in the axes array is a -1.0 to 1.0 float that tell you exactly where a joystick is or how far a trigger has been pulled.

Page 52: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Screen Orientation API

Must-have on mobile devices

The Screen Orientation API allows you to do things like changing and locking, you guessed it, the orientation of the screen.

Before now, it’s been incredibly difficult to lock orientation on a website or game using nothing but JavaScript.

https://bugzilla.mozilla.org/show_bug.cgi?id=740188http://dvcs.w3.org/hg/screen-orientation/raw-file/default/Overview.html

Page 53: MDN Hackday London - Open Web Games with HTML5 & JavaScript

screen.mozLockOrientation('landscape');

Screen Orientation API

The Screen Orientation API is another relatively simple one.

It just landed in Firefox Nightly on mobile.

All you need to do is call the ‘lockOrientation’ method of the screen object and pass it a orientation string.

It’s important to note that you also need to be using the Full Screen API for the orientation lock to work.

Page 54: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games with HTML5 & JavaScript

It’s something we’re spending a lot of time on at Mozilla.

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

https://apps.mozillalabs.comhttps://developer.mozilla.org/en/OpenWebApps

Page 56: MDN Hackday London - Open Web Games 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 57: MDN Hackday London - Open Web Games 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.

Page 58: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games 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: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Keeping up

So much stuff on the horizon

I’ve really only touched the tip of the iceberg here.

There is much more coming in the near future.

Here are a few ways to keep up with things and get yourself prepared, particularly the things happening at Mozilla.

Page 63: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Are We Fun Yet?

https://wiki.mozilla.org/Platform/AreWeFunYet

Page 64: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Firefox Aurora

“Get a first look at the latest developer tools, security features and innovative HTML5 and other Web technologies.”

http://www.mozilla.org/en-US/firefox/channel/#aurora

Page 65: MDN Hackday London - Open Web Games with HTML5 & JavaScript

Firefox Nightly

Bleeding edge functionality.

Testing only.

http://nightly.mozilla.org

Page 66: MDN Hackday London - Open Web Games 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

Slidesslideshare.net/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

These slides are online at slideshare.net/robhawkes