Skip to content

Instantly share code, notes, and snippets.

@parasyte parasyte/mp.js
Last active Dec 16, 2015

Embed
What would you like to do?
Multiplayer example for melonJS with PubNub
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 : "my_game",
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 if (typeof(this.new_player) === "function") {
// Create a new object with the given UUID
var x = obj.pos && obj.pos.x || 50;
var y = obj.pos && obj.pos.y || 50;
if (!(obj = this.new_player(x, y)))
return;
obj.name = msg.UUID;
}
// Route message
switch (msg.action) {
case "update":
// Position update
obj.pos.setV(msg.pos);
obj.vel.setV(msg.vel);
break;
case "key":
if (msg.key == "jump")
obj.doJump();
break;
}
},
sendMessage : function (msg) {
msg.UUID = this.UUID;
this.pubnub.publish({
channel : "my_game",
message : msg
});
}
});
/* EXAMPLE */
// Create a new Multiplayer object
var mp = new Multiplayer(function (x, y) {
var obj = new me.ObjectEntity(x, y, {
name : mp.UUID,
image : "my_sprite",
sprite_width : 32,
sprite_height : 32
});
me.game.add(obj, 4);
me.game.sort();
return obj;
});
// Create a player object that I control
var my_obj = new me.ObjectEntity(50, 50, {
name : mp.UUID,
image : "my_sprite",
sprite_width : 32,
sprite_height : 32
});
// Send my object position periodically
setTimeout(function () {
// Simulate the object moving randomly
my_obj.pos.x += ~~(Math.random() * 8) - 4;
my_obj.pos.y += ~~(Math.random() * 8) - 4;
// Send update
mp.sendMessage({
action : "update",
pos : my_obj.pos,
vel : me_obj.vel
});
}, 250);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.