SlideShare a Scribd company logo
Realtime HTML5 Multiplayer Games with Node.js
http://holiday2010.ogilvy.com
Benefits of writing your game in JavaScript with Node.js JavaScript is a great language Node.JS and V8 are very fast Interoperability between the client and the server  Shared code base means no translation layer or violating DRY principal Many JavaScript libraries already exist to help your game do cool stuff When writing your game no mental model shift required when switching back and fourth
RealtimeMultiplayerGame.namespace("RealtimeMultiplayerGame.model"); RealtimeMultiplayerGame.model.NetChannelMessage = function(aSequenceNumber, aClientid, isReliable, aCommandType, aPayload) { this.seq = aSequenceNumber; this.id = aClientid;         // Server gives us one when we first  connect to it this.cmd = aCommandType; this.payload = aPayload; this.messageTime = -1; this.isReliable = isReliable; }; RealtimeMultiplayerGame.model.NetChannelMessage.prototype = { isReliable : false, cmd : 0, aPayload : null, seq : -1, id : -1, messageTime : -1, encodeSelf: function() { ... }          decodeSelf: function() { ... } } Interoperability between Client and Server Key Take Away: The fancier you make things, the more you benefit from this. No middle man layer to introduce bugs Example - Shared NetworkMessage class
Well that's cool, let's write a game now! ...problems arose
The initial  (naive)  approach Clients send information about their player to the server:      var info = {};      info.position = {x:10, y:15};      info.velocity = {x:0.5,y: 0.2};      info.currentWeapon = 1;      info.radius = 10;      this.netChannel.send( info ); Server re-broadcast that info to all other clients: function broadcastInfo( sendingClient, messageInfo ) {      for(var aClient in allClients) {          if(aClient != sendingClient) {              aClient.connection.send( messageInfo );          }                  }   }
Problems with this approach We cannot trust users to give us correct info Position?   Everywhere Velocity?  Infinite Weapon fire hit other player?   Yes! Twice!   (and both were headshots)   Health? Number.MAX_VALUE
Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
A Different Approach Server / Client Model
Server / Client Model
Rendering the world Our nervous system is actually designed to work around latency If we can apply a constant smooth latency to an object it is easy for a human being to adjust 
Entity Interpolation Smoothly moving between two known world updates
 
RealtimeMultiplayerNodeJS Demos / Repo http://bit.ly/RealtimeMultiplayerNodeJs
Questions? Mario Gonzalez Senior Applications Developer Ogilvy & Mather, New York mariogonzalez [at] gmail [dot] com https://www.github.com/onedayitwillmake http://www.onedayitwillmake.com @1dayitwillmake

More Related Content

PDF
Be IT Conference 2015 | MentorMate - Adding multiplayer to your mobile game: ...
PPTX
Data Center TCP (DCTCP)
PPTX
Civil rights movement
PPT
PDF
Digital photo journal1
PDF
Listino Base Primavera 2011
PPTX
Teens helping each other 2
Be IT Conference 2015 | MentorMate - Adding multiplayer to your mobile game: ...
Data Center TCP (DCTCP)
Civil rights movement
Digital photo journal1
Listino Base Primavera 2011
Teens helping each other 2

Similar to Realtime html5 multiplayer_games_with_node_js (20)

PPT
Realtime html5 multiplayer_games_with_node_js
PDF
Pushing the Web: Interesting things to Know
PPTX
Maintaining Your Code Clint Eastwood Style
PDF
Comet from JavaOne 2008
PDF
Sony C#/.NET component set analysis
PPTX
Lambdas puzzler - Peter Lawrey
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
ODP
Introduce about Nodejs - duyetdev.com
PDF
DZone_RC_RxJS
KEY
Writing robust Node.js applications
PDF
A Closer Look At React Native
PPT
When Web Services Go Bad
PDF
Application metrics - Confoo 2019
PDF
soft-shake.ch - Hands on Node.js
PPTX
Game server development in node.js in jsconf eu
PPT
Ember.js Tokyo event 2014/09/22 (English)
PDF
Application Metrics (with Prometheus examples)
PDF
Programming Without Coding Technology (PWCT) Features - Programming Paradigm
PDF
Node.js vs Play Framework
PDF
Java vs. Java Script for enterprise web applications - Chris Bailey
Realtime html5 multiplayer_games_with_node_js
Pushing the Web: Interesting things to Know
Maintaining Your Code Clint Eastwood Style
Comet from JavaOne 2008
Sony C#/.NET component set analysis
Lambdas puzzler - Peter Lawrey
Event-driven IO server-side JavaScript environment based on V8 Engine
Introduce about Nodejs - duyetdev.com
DZone_RC_RxJS
Writing robust Node.js applications
A Closer Look At React Native
When Web Services Go Bad
Application metrics - Confoo 2019
soft-shake.ch - Hands on Node.js
Game server development in node.js in jsconf eu
Ember.js Tokyo event 2014/09/22 (English)
Application Metrics (with Prometheus examples)
Programming Without Coding Technology (PWCT) Features - Programming Paradigm
Node.js vs Play Framework
Java vs. Java Script for enterprise web applications - Chris Bailey
Ad

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Cloud computing and distributed systems.
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
A Presentation on Artificial Intelligence
PDF
Machine learning based COVID-19 study performance prediction
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
The AUB Centre for AI in Media Proposal.docx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Per capita expenditure prediction using model stacking based on satellite ima...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Assigned Numbers - 2025 - Bluetooth® Document
Cloud computing and distributed systems.
A comparative analysis of optical character recognition models for extracting...
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
A Presentation on Artificial Intelligence
Machine learning based COVID-19 study performance prediction
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Ad

Realtime html5 multiplayer_games_with_node_js

  • 1. Realtime HTML5 Multiplayer Games with Node.js
  • 3. Benefits of writing your game in JavaScript with Node.js JavaScript is a great language Node.JS and V8 are very fast Interoperability between the client and the server  Shared code base means no translation layer or violating DRY principal Many JavaScript libraries already exist to help your game do cool stuff When writing your game no mental model shift required when switching back and fourth
  • 4. RealtimeMultiplayerGame.namespace("RealtimeMultiplayerGame.model"); RealtimeMultiplayerGame.model.NetChannelMessage = function(aSequenceNumber, aClientid, isReliable, aCommandType, aPayload) { this.seq = aSequenceNumber; this.id = aClientid;         // Server gives us one when we first  connect to it this.cmd = aCommandType; this.payload = aPayload; this.messageTime = -1; this.isReliable = isReliable; }; RealtimeMultiplayerGame.model.NetChannelMessage.prototype = { isReliable : false, cmd : 0, aPayload : null, seq : -1, id : -1, messageTime : -1, encodeSelf: function() { ... }         decodeSelf: function() { ... } } Interoperability between Client and Server Key Take Away: The fancier you make things, the more you benefit from this. No middle man layer to introduce bugs Example - Shared NetworkMessage class
  • 5. Well that's cool, let's write a game now! ...problems arose
  • 6. The initial (naive)  approach Clients send information about their player to the server:      var info = {};      info.position = {x:10, y:15};      info.velocity = {x:0.5,y: 0.2};      info.currentWeapon = 1;      info.radius = 10;      this.netChannel.send( info ); Server re-broadcast that info to all other clients: function broadcastInfo( sendingClient, messageInfo ) {     for(var aClient in allClients) {         if(aClient != sendingClient) {              aClient.connection.send( messageInfo );          }                  }   }
  • 7. Problems with this approach We cannot trust users to give us correct info Position?   Everywhere Velocity?  Infinite Weapon fire hit other player?   Yes! Twice!   (and both were headshots)   Health? Number.MAX_VALUE
  • 8. Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
  • 9. Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
  • 10. Problems with this approach When you draw based on last received network information, you can never represent a the true motion path (the "bouncing ball" problem)
  • 11. A Different Approach Server / Client Model
  • 13. Rendering the world Our nervous system is actually designed to work around latency If we can apply a constant smooth latency to an object it is easy for a human being to adjust 
  • 14. Entity Interpolation Smoothly moving between two known world updates
  • 15.  
  • 16. RealtimeMultiplayerNodeJS Demos / Repo http://bit.ly/RealtimeMultiplayerNodeJs
  • 17. Questions? Mario Gonzalez Senior Applications Developer Ogilvy & Mather, New York mariogonzalez [at] gmail [dot] com https://www.github.com/onedayitwillmake http://www.onedayitwillmake.com @1dayitwillmake

Editor's Notes

  • #3: For Ogily's 2011 Holiday Card, we decided to make an HTML5 game We decided that the game should be created in HTML5, and having heard of Node.JS and Socket.IO slightly we decided that we should create a multiplayer game The game is located at http://holiday2010.ogilvy.com, To say something about Node.js, the game has been running without a restart since around December 22nd and thousands of games have been played
  • #4: * Javascript is a really great language for writing games, it has all the tools you could ask for due to it's dynamic nature * Node.JS and the V8 engine is extreme fast, on our game the node.js process is using only 1 thread and runs at about 3-4% CPU usage while running 8 simultaneous games each with their own collision engine instance  * The client and the server are both running javascript. This means that we can share logic between both when needed.  For example having a Vector math utility class. Another example in our case was the NetworkMessage class. Even though the server is the authoritative source, and is the one that is actually running the game. It can be beneficial to share some piece of logic between the two * Many javascript libraries exist, relating to cool game stuff. With Node.js using one of those libraries to help you create your game is relatively easy to do.  Example: Box2D js implementation!   * Finally because the client and the server are both running in javascript. It makes it a lot easier to write a cohesive game. Switching between different mental models be it java or python or a C++ backed server can make you lose focus on writing the game
  • #6: Well, those pieces are in place so let's just start writing a game and see what happens. My favorite, famous last words are "...all you gotta do now is...."
  • #8: The main problem with this approach is that we cannot trust the users to provide us with correct information about their current state. A nefarious can enter the game, and report that other plays projectiles never collide with them, and that their health is always Number.MAX_VALUE
  • #9: Another problem with this approach is determining where the collision takes place.  If you're locally playing the game, and placing users at their last reported position -  it might appear that you have hit the other player with your projectile, however when the server checks this information will report that your projectile was and that player in fact did not collide. This is obviously a very large problem, because it also happens in reverse.  You can locally dodge a projectile narrowly however, when that data gets to the server, you have already been considered hit.
  • #10: A problem with this approach is that as we receive new position and velocity information regarding an entity from the server, when we draw the entity using this information it causes an abrupt shift in motion, and we will continue along this motion path until new more update information is received from the server. Players and entities tend to be very jumpy, so as they move around they are rarely traveling along a straight path and velocity is usually damped. This is sometimes referred to as the bouncing ball problem, because if you visualize the parabola of a ball thrown in the air as gravity accumulates and  eventually sends it back down smoothly. It is very difficult to achieve that motion using only the last instantaneous velocity information  ---- The dotted lines represent times when we receive new information from the server. The red line represents the drawn path that uses only last instantaneous velocity will move along the incorrect path continuously and when it receives newer updated information will move using the velocity at that time This problem can be lessoned by receiving more world state samples from the server. 
  • #11: Another problem with this approach is packet loss.  If one of the packets as shown by the dotted lines is dropped, the user will travel along an incorrect path for a longer period of time. Of course this time is measured in milliseconds so it's not the end of the world. However in action, it feels very wrong visually because things don't change position instantnously in real life
  • #13: So I decided to look around, and see how this was generally done. After all people have been making realtime multiplayer games for a while now. I found some interesting sources of information, specifically the QuakeWorld source code as well as some Valve white papers on networking In this approach there is a single authoritative server which is playing the game, and clients only send their sampled input data For example, i send only the fact that my spacebar key is being pressed down the server decides what that means in terms of the game and when it decided i can -  -- With this model we completely sidestep many problems of previous implementation Cheating is also made more difficult slightly, because at most a player can tell us 'hey all my keys are being pressed' which does not really gain them anything anyway.
  • #14: Human beings are very good at adapting to a latency, and predicting what will happen on the short term scale. This is when i had the eureka moment going through some of valves Source engine wiki. The key piece of the puzzle is that we render all clients N milliseconds backwards in time at all times. This number is an arbitrary number, so i'm going to go with 75 for the rest of the presentation
  • #15: So we set up a system in place, where the client receives a high fidelity updates from the server at a discrete interval We store those WorldUpdates in an array. When it comes time to draw the  world on the players screen we simply draw them at   currentTime - interpAmount  We'll call this value renderTime, which again is simply the currentTime minus 75 milliseconds To do every render, we first find the two updates that our renderTime falls between with a simple loop Once we find those two updates  we use a Linear interpolation function to  position our object precisely along it's path. If a packet is dropped, for example if we never receive packet 343 on this slide we can still render between two known packets 342 and 344
  • #16: Using RealtimeMultiplayerNodeJS
  • #17: So those ideas are how we built our multiplayer game and I think while somewhat naive itself, the implementation of these concepts into javascript has a interesting value and javascript game developers could use this and create interesting things So we took the idea and decided to re-write that portion of the game and create it as it's own project and now i'm going to show two demo's of this