SlideShare uma empresa Scribd logo
1 de 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!

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Último (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

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!