SlideShare ist ein Scribd-Unternehmen logo
1 von 11
Lightweight
Multiplayer
HTML5 Games
with PubNub
and melonJS
By Jay Oster
Can a web browser be used as a platform for serious gaming? Here at
PubNub, we intended to find out, and decided to experiment with an
HTML5 game engine. melonJS is the tool of choice because it’s
lightweight, runs well on mobile, and is very easy to use. One question
that always comes up on the melonJS forum is the best way to use
Node.js/socket.io to build multiplayer games. In this article, we will be
using PubNub, but many of the techniques can be applied to socket.io as
well.
For this experiment, we start with the platformer demo that ships with
the melonJS 0.9.7 source code, and transform it into a multiplayer game
with just a few extra lines of code. And all without any servers! This is only
possible with the power provided by PubNub.
Want to see the end result? Check it out here. We’ll walk you through how
to add multiplayer support to your own game below:
Download melonJS
First step, clone the git repository and checkout the 0.9.7 tag:
Next, you’ll want to follow the build instructions to build the library. And you can test the vanilla
platformer demo by launching an HTTP server with Python:
Now visit the URL in your favorite web browser:
It’s a very simple game demo, with a handful of enemies and two maps. However, we want
multiplayer support as well. What we started with is a simple module to handle the multiplayer
communications:
$ git clone https://github.com/melonjs/melonjs.git
$ cd melonJS
$ git checkout 0.9.7
$ python –m SimpleHTTPServer
http://localhost:8000/examples/platformer/
mp.js
var Multiplayer = Object.extend({
init : function (new_player) {
this.pubnub = PUBNUB.init({
publish_key : "demo",
subscribe_key : "demo"
});
this.new_player = new_player;
// Record my UUID, so I don't process my own messages
this.UUID = this.pubnub.uuid();
// Listen for incoming messages
this.pubnub.subscribe({
channel : "PubNub-melonJS-demo",
message : this.handleMessage.bind(this)
});
},
handleMessage : function (msg) {
// Did I send this message?
if (msg.UUID === this.UUID)
return;
// Get a reference to the object for the player that
sent
// this message
var obj = me.game.getEntityByName(msg.UUID);
if (obj.length)
{
obj = obj[0];
}
else {
var x = obj.pos && obj.pos.x || 50;
var y = obj.pos && obj.pos.y || 50;
obj = this.new_player(x, y);
obj.name = msg.UUID;
}
// Route message
switch (msg.action) {
case "update":
// Position update
obj.pos.setV(msg.pos);
obj.vel.setV(msg.vel);
break;
// TODO: Define more actions here
}
},
sendMessage : function (msg) {
msg.UUID = this.UUID;
this.pubnub.publish({
channel : "PubNub-melonJS-demo",
message : msg
});
}
});
mp.js
This class has a constructor and two methods; the constructor takes one callback, and
the sendMessage() method is the one we’ll be using to send game state updates. This module also
does some useful things like creating new player objects, and handling player position updates. We
placed this file (mp.js) into the platformer directory, and included it within index.html (along with
pubnub-3.4.5-min.js)
Creating a new Multiplayer object
To initialize the Multiplayer object, we added a few lines after the level has been loaded, around line
104:
// Instantiate the Multiplayer object
game.mp = new Multiplayer(function (x, y) {
// Create a new player object
var obj = me.entityPool.newInstanceOf("mainplayer",
x, y, {
spritewidth : 72,
spriteheight : 98,
isMP : true
});
me.game.add(obj, 4);
me.game.sort();
return obj;
});
This creates the object, placing a reference into the game namespace as game.mp , and passes a callback function that
will create new player objects when we receive messages from other players we haven’t seen before.
That isMP : true line is important! It will be used later to determine whether the player object is Keyboard-controlled, or
controlled by messages from the network.
Creating a new Multiplayer object
Side note: to make testing easier, you can disable the “automatic pause” feature when navigating
away from the browser window. We added the following line just before the call to me.video.init() in
main.js:
me.sys.pauseOnBlur = false;
Turning the PlayerEntity object into a Multi-PlayerEntity Object
Now we’re ready to hack the PlayerEntity object to work in a multiplayer environment, sending
position updates, and ignoring the keyboard input for the isMP entities. Starting in entities.js at line 25,
we added two new properties:
this.isMP = settings.isMP;
this.step = 0;
Then we changed the following lines to be conditional on the value of the isMP property. The viewport
follow and key bindings should be skipped if the entity is a multiplayer object:
if (!this.isMP) {
// set the display around our position
/* ... snip */
// enable keyboard
/* ... snip */
}
Turning the PlayerEntity object into a Multi-PlayerEntity Object
The original code has been snipped from the example above, but it should be pretty obvious what
needs to be changed here.
In the PlayerEntity.update() method, there are a few things that also need to be made conditional on
the value of isMP. This first checks the key status:
if (!this.isMP) {
if (me.input.isKeyPressed('left')) {
/* ... snip */
}
if (me.input.isKeyPressed('jump')) {
/* ... snip */
}
}
Turning the PlayerEntity object into a Multi-PlayerEntity Object
There’s also a call to me.game.viewport.fadeIn() that reloads the level when the player falls into a hole. We could make that
conditional too, if we don’t want to reload the level when other players fall in.
And finally, there’s a comment at the end of the method about checking if the player has moved. This is the perfect hook for sending out
player position updates to other players! We added the following code just before the call to this.parent() :
if (this.vel.x !== 0)
this.flipX(this.vel.x < 0);
if (!this.isMP) {
// Check if it's time to send a message
if (this.step == 0) {
game.mp.sendMessage({
action : "update",
pos : {
x : this.pos.x,
y : this.pos.y
},
vel : {
x : this.vel.x,
y : this.vel.y
}
});
}
if (this.step++ > 3)
this.step = 0;
}
The first two lines will fix the “direction” of the player object when it is
updated by a message from the network.
The rest contains a basic counter to prevent sending messages too
fast, and the final message publish that other players will receive.
Play It Online!
The final demo can be played online now!
And you can also have a peek at the full
patch here. A much better approach
would be separating control logic entirely
from the entity. But in this case, the demo
serves its purpose. Maybe next time, we
can work on synchronizing more of the
game state, like enemy positions and
individual score counters!

Weitere ähnliche Inhalte

Was ist angesagt?

Introdução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinIntrodução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinNelson Glauber Leal
 
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018Codemotion
 
Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbikailan
 
Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2Brian Schott
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-pythonEric Ahn
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to NodejsGabriele Lana
 
DevOps(2) : Vagrant - (MOSG)
DevOps(2) : Vagrant  -  (MOSG)DevOps(2) : Vagrant  -  (MOSG)
DevOps(2) : Vagrant - (MOSG)Soshi Nemoto
 
Ansible with-junos
Ansible with-junosAnsible with-junos
Ansible with-junosAkhmad Zaimi
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perldeepfountainconsulting
 
Ansible を完全にマスターする
Ansible を完全にマスターするAnsible を完全にマスターする
Ansible を完全にマスターするKeisuke Kamada
 
Release responsibly (Maintaining Backwards Compatibility)
Release responsibly (Maintaining Backwards Compatibility)Release responsibly (Maintaining Backwards Compatibility)
Release responsibly (Maintaining Backwards Compatibility)Emily Stolfo
 
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek Meet
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek MeetBringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek Meet
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek MeetRobert Nyman
 

Was ist angesagt? (16)

Introdução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com KotlinIntrodução ao Desenvolvimento Android com Kotlin
Introdução ao Desenvolvimento Android com Kotlin
 
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018
Max Gallo - You don't know MobX State Tree - Codemotion Milan 2018
 
Rapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodbRapid web development using tornado web and mongodb
Rapid web development using tornado web and mongodb
 
JavaScript on the Desktop
JavaScript on the DesktopJavaScript on the Desktop
JavaScript on the Desktop
 
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2Using Ansible Dynamic Inventory with Amazon EC2
Using Ansible Dynamic Inventory with Amazon EC2
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Introduction to Nodejs
Introduction to NodejsIntroduction to Nodejs
Introduction to Nodejs
 
DevOps(2) : Vagrant - (MOSG)
DevOps(2) : Vagrant  -  (MOSG)DevOps(2) : Vagrant  -  (MOSG)
DevOps(2) : Vagrant - (MOSG)
 
Ansible with-junos
Ansible with-junosAnsible with-junos
Ansible with-junos
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
Network
NetworkNetwork
Network
 
Ansible を完全にマスターする
Ansible を完全にマスターするAnsible を完全にマスターする
Ansible を完全にマスターする
 
Release responsibly (Maintaining Backwards Compatibility)
Release responsibly (Maintaining Backwards Compatibility)Release responsibly (Maintaining Backwards Compatibility)
Release responsibly (Maintaining Backwards Compatibility)
 
Virtualbox and Mysql
Virtualbox and MysqlVirtualbox and Mysql
Virtualbox and Mysql
 
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek Meet
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek MeetBringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek Meet
Bringing the Open Web & APIs to 
mobile devices with Firefox OS - Geek Meet
 

Andere mochten auch

Rails missing features
Rails missing featuresRails missing features
Rails missing featuresAstrails
 
What the heck is a realtime app?
What the heck is a realtime app?What the heck is a realtime app?
What the heck is a realtime app?PubNub
 
Global Data Stream Network for Internet of Things
Global Data Stream Network for Internet of ThingsGlobal Data Stream Network for Internet of Things
Global Data Stream Network for Internet of ThingsBhavana Srinivas
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureFrank Greco
 
5 Best Practices for Cost-Efficient User Acquisition
5 Best Practices for Cost-Efficient User Acquisition5 Best Practices for Cost-Efficient User Acquisition
5 Best Practices for Cost-Efficient User AcquisitionChartboost
 
How to Decrease Costly User Acquisition Costs The Uber Way
How to Decrease Costly User Acquisition Costs The Uber WayHow to Decrease Costly User Acquisition Costs The Uber Way
How to Decrease Costly User Acquisition Costs The Uber WaySociable Labs
 

Andere mochten auch (6)

Rails missing features
Rails missing featuresRails missing features
Rails missing features
 
What the heck is a realtime app?
What the heck is a realtime app?What the heck is a realtime app?
What the heck is a realtime app?
 
Global Data Stream Network for Internet of Things
Global Data Stream Network for Internet of ThingsGlobal Data Stream Network for Internet of Things
Global Data Stream Network for Internet of Things
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
5 Best Practices for Cost-Efficient User Acquisition
5 Best Practices for Cost-Efficient User Acquisition5 Best Practices for Cost-Efficient User Acquisition
5 Best Practices for Cost-Efficient User Acquisition
 
How to Decrease Costly User Acquisition Costs The Uber Way
How to Decrease Costly User Acquisition Costs The Uber WayHow to Decrease Costly User Acquisition Costs The Uber Way
How to Decrease Costly User Acquisition Costs The Uber Way
 

Ähnlich wie Lightweight Multiplayer HTML5 Games with PubNub

School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Node.js basics
Node.js basicsNode.js basics
Node.js basicsBen Lin
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfudit652068
 
The Ring programming language version 1.5.2 book - Part 48 of 181
The Ring programming language version 1.5.2 book - Part 48 of 181The Ring programming language version 1.5.2 book - Part 48 of 181
The Ring programming language version 1.5.2 book - Part 48 of 181Mahmoud Samir Fayed
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 MinigamesSusan Gold
 
Mp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMontreal Python
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmusBram Vogelaar
 
Realtime html5 multiplayer_games_with_node_js
Realtime html5 multiplayer_games_with_node_jsRealtime html5 multiplayer_games_with_node_js
Realtime html5 multiplayer_games_with_node_jsMario Gonzalez
 
Java term project final report
Java term project final reportJava term project final report
Java term project final reportJiwon Han
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.jsjubilem
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in OdooOdoo
 
Noughts and Crosses Design Information
Noughts and Crosses Design InformationNoughts and Crosses Design Information
Noughts and Crosses Design InformationChristopher Orchard
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
Non stop random2b
Non stop random2bNon stop random2b
Non stop random2bphanhung20
 
Unity3d scripting tutorial
Unity3d scripting tutorialUnity3d scripting tutorial
Unity3d scripting tutorialhungnttg
 
How tomakea gameinunity3d
How tomakea gameinunity3dHow tomakea gameinunity3d
How tomakea gameinunity3dDao Tung
 
I really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdfI really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdfaggarwalshoppe14
 
Asynchronous Programming with JavaScript
Asynchronous Programming with JavaScriptAsynchronous Programming with JavaScript
Asynchronous Programming with JavaScriptWebF
 

Ähnlich wie Lightweight Multiplayer HTML5 Games with PubNub (20)

School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
Node.js basics
Node.js basicsNode.js basics
Node.js basics
 
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdfWorking with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
Working with Layout Managers. Notes 1. In part 2, note that the Gam.pdf
 
ChatGPT in Education
ChatGPT in EducationChatGPT in Education
ChatGPT in Education
 
The Ring programming language version 1.5.2 book - Part 48 of 181
The Ring programming language version 1.5.2 book - Part 48 of 181The Ring programming language version 1.5.2 book - Part 48 of 181
The Ring programming language version 1.5.2 book - Part 48 of 181
 
Gdc09 Minigames
Gdc09 MinigamesGdc09 Minigames
Gdc09 Minigames
 
Mp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook gameMp24: The Bachelor, a facebook game
Mp24: The Bachelor, a facebook game
 
Testing your infrastructure with litmus
Testing your infrastructure with litmusTesting your infrastructure with litmus
Testing your infrastructure with litmus
 
Realtime html5 multiplayer_games_with_node_js
Realtime html5 multiplayer_games_with_node_jsRealtime html5 multiplayer_games_with_node_js
Realtime html5 multiplayer_games_with_node_js
 
Java term project final report
Java term project final reportJava term project final report
Java term project final report
 
From Ruby to Node.js
From Ruby to Node.jsFrom Ruby to Node.js
From Ruby to Node.js
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
Noughts and Crosses Design Information
Noughts and Crosses Design InformationNoughts and Crosses Design Information
Noughts and Crosses Design Information
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
Non stop random2b
Non stop random2bNon stop random2b
Non stop random2b
 
Unity3d scripting tutorial
Unity3d scripting tutorialUnity3d scripting tutorial
Unity3d scripting tutorial
 
How tomakea gameinunity3d
How tomakea gameinunity3dHow tomakea gameinunity3d
How tomakea gameinunity3d
 
I really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdfI really need some help if I have this right so far. PLEASE CHANG.pdf
I really need some help if I have this right so far. PLEASE CHANG.pdf
 
Asynchronous Programming with JavaScript
Asynchronous Programming with JavaScriptAsynchronous Programming with JavaScript
Asynchronous Programming with JavaScript
 

Kürzlich hochgeladen

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 

Kürzlich hochgeladen (20)

Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 

Lightweight Multiplayer HTML5 Games with PubNub

  • 2. Can a web browser be used as a platform for serious gaming? Here at PubNub, we intended to find out, and decided to experiment with an HTML5 game engine. melonJS is the tool of choice because it’s lightweight, runs well on mobile, and is very easy to use. One question that always comes up on the melonJS forum is the best way to use Node.js/socket.io to build multiplayer games. In this article, we will be using PubNub, but many of the techniques can be applied to socket.io as well. For this experiment, we start with the platformer demo that ships with the melonJS 0.9.7 source code, and transform it into a multiplayer game with just a few extra lines of code. And all without any servers! This is only possible with the power provided by PubNub. Want to see the end result? Check it out here. We’ll walk you through how to add multiplayer support to your own game below:
  • 3. Download melonJS First step, clone the git repository and checkout the 0.9.7 tag: Next, you’ll want to follow the build instructions to build the library. And you can test the vanilla platformer demo by launching an HTTP server with Python: Now visit the URL in your favorite web browser: It’s a very simple game demo, with a handful of enemies and two maps. However, we want multiplayer support as well. What we started with is a simple module to handle the multiplayer communications: $ git clone https://github.com/melonjs/melonjs.git $ cd melonJS $ git checkout 0.9.7 $ python –m SimpleHTTPServer http://localhost:8000/examples/platformer/
  • 4. mp.js var Multiplayer = Object.extend({ init : function (new_player) { this.pubnub = PUBNUB.init({ publish_key : "demo", subscribe_key : "demo" }); this.new_player = new_player; // Record my UUID, so I don't process my own messages this.UUID = this.pubnub.uuid(); // Listen for incoming messages this.pubnub.subscribe({ channel : "PubNub-melonJS-demo", message : this.handleMessage.bind(this) }); }, handleMessage : function (msg) { // Did I send this message? if (msg.UUID === this.UUID) return; // Get a reference to the object for the player that sent // this message var obj = me.game.getEntityByName(msg.UUID); if (obj.length) { obj = obj[0]; } else { var x = obj.pos && obj.pos.x || 50; var y = obj.pos && obj.pos.y || 50; obj = this.new_player(x, y); obj.name = msg.UUID; } // Route message switch (msg.action) { case "update": // Position update obj.pos.setV(msg.pos); obj.vel.setV(msg.vel); break; // TODO: Define more actions here } }, sendMessage : function (msg) { msg.UUID = this.UUID; this.pubnub.publish({ channel : "PubNub-melonJS-demo", message : msg }); } });
  • 5. mp.js This class has a constructor and two methods; the constructor takes one callback, and the sendMessage() method is the one we’ll be using to send game state updates. This module also does some useful things like creating new player objects, and handling player position updates. We placed this file (mp.js) into the platformer directory, and included it within index.html (along with pubnub-3.4.5-min.js)
  • 6. Creating a new Multiplayer object To initialize the Multiplayer object, we added a few lines after the level has been loaded, around line 104: // Instantiate the Multiplayer object game.mp = new Multiplayer(function (x, y) { // Create a new player object var obj = me.entityPool.newInstanceOf("mainplayer", x, y, { spritewidth : 72, spriteheight : 98, isMP : true }); me.game.add(obj, 4); me.game.sort(); return obj; }); This creates the object, placing a reference into the game namespace as game.mp , and passes a callback function that will create new player objects when we receive messages from other players we haven’t seen before. That isMP : true line is important! It will be used later to determine whether the player object is Keyboard-controlled, or controlled by messages from the network.
  • 7. Creating a new Multiplayer object Side note: to make testing easier, you can disable the “automatic pause” feature when navigating away from the browser window. We added the following line just before the call to me.video.init() in main.js: me.sys.pauseOnBlur = false;
  • 8. Turning the PlayerEntity object into a Multi-PlayerEntity Object Now we’re ready to hack the PlayerEntity object to work in a multiplayer environment, sending position updates, and ignoring the keyboard input for the isMP entities. Starting in entities.js at line 25, we added two new properties: this.isMP = settings.isMP; this.step = 0; Then we changed the following lines to be conditional on the value of the isMP property. The viewport follow and key bindings should be skipped if the entity is a multiplayer object: if (!this.isMP) { // set the display around our position /* ... snip */ // enable keyboard /* ... snip */ }
  • 9. Turning the PlayerEntity object into a Multi-PlayerEntity Object The original code has been snipped from the example above, but it should be pretty obvious what needs to be changed here. In the PlayerEntity.update() method, there are a few things that also need to be made conditional on the value of isMP. This first checks the key status: if (!this.isMP) { if (me.input.isKeyPressed('left')) { /* ... snip */ } if (me.input.isKeyPressed('jump')) { /* ... snip */ } }
  • 10. Turning the PlayerEntity object into a Multi-PlayerEntity Object There’s also a call to me.game.viewport.fadeIn() that reloads the level when the player falls into a hole. We could make that conditional too, if we don’t want to reload the level when other players fall in. And finally, there’s a comment at the end of the method about checking if the player has moved. This is the perfect hook for sending out player position updates to other players! We added the following code just before the call to this.parent() : if (this.vel.x !== 0) this.flipX(this.vel.x < 0); if (!this.isMP) { // Check if it's time to send a message if (this.step == 0) { game.mp.sendMessage({ action : "update", pos : { x : this.pos.x, y : this.pos.y }, vel : { x : this.vel.x, y : this.vel.y } }); } if (this.step++ > 3) this.step = 0; } The first two lines will fix the “direction” of the player object when it is updated by a message from the network. The rest contains a basic counter to prevent sending messages too fast, and the final message publish that other players will receive.
  • 11. Play It Online! The final demo can be played online now! And you can also have a peek at the full patch here. A much better approach would be separating control logic entirely from the entity. But in this case, the demo serves its purpose. Maybe next time, we can work on synchronizing more of the game state, like enemy positions and individual score counters!