Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Last active September 5, 2017 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/bf0c6c5b3f90763457943037b718d3b9 to your computer and use it in GitHub Desktop.
Save joduplessis/bf0c6c5b3f90763457943037b718d3b9 to your computer and use it in GitHub Desktop.
Simplistic example showing multiplayer movement in the browser. This works off a simple websocket server.
"use strict" ;
function init() {
let socket = io('http://localhost:3000');
let div = document.createElement("div");
let top = 10 ;
let left = 10 ;
let movementIncrement = 5 ;
let randomNumber = Math.random() + "" ;
let thisPlayersId = "player"+randomNumber.split('.')[1] ;
socket.emit('createplayer', { 'id': thisPlayersId, 'x': left++, 'y': top }) ;
// update players on the page
socket.on('updateplayers', function(packet) {
for (let x = 0 ; x < packet.length ; x++ ) {
let getDiv = document.getElementById(packet[x].id) ;
if ( getDiv==null )
createPlayer(packet[x].id,packet[x].x,packet[x].y) ;
else
updatePlayer(getDiv,packet[x].x,packet[x].y) ;
}
}) ;
socket.on('removeplayer', function(packet) {
document.getElementById(packet).remove();
});
// user interaction
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if ( e.keyCode == "40")
top = top + movementIncrement ;
if ( e.keyCode == "38")
top = top - movementIncrement ;
if ( e.keyCode == "37")
left = left - movementIncrement ;
if ( e.keyCode == "39")
left = left + movementIncrement;
socket.emit('setplayer', { 'id': thisPlayersId, 'x': left, 'y': top }) ;
}
}
function updatePlayer(div,x,y) {
div.style.top = y+"px" ;
div.style.left = x+"px" ;
}
function createPlayer(id,x,y) {
let adiv = document.createElement("div");
adiv.id = id ;
adiv.style.width = "10px";
adiv.style.height = "10px";
adiv.style.position = "absolute";
adiv.style.top = x+"px";
adiv.style.left = y+"px";
adiv.style.background = "#00aa00";
document.body.appendChild(adiv);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment