Game Development Reference
In-Depth Information
When the connection is created, the server emits a login event. The client responds
to the server with the username player for the playing user, and the username
spectator for the other user, as shown in the following code:
socket.on('login', function() {
socket.emit('login', "player");
});
The client responds to the logged-in server event and emits the join event with the
room name ourgame as a parameter, as shown in the following code:
socket.on('loggedIn', function(content) {
console.log(content);
var messageObj=JSON.parse(content);
if(messageObj.username=="you")
socket.emit('join', "ourgame");
});
socket.on('roomJoined', function(content) {
console.log(content);
});
On serverMessage , the client invokes the applyData function. The applyData
function parses the response and checks the messageObj.username parameter. If the
value is not you , it updates the game state. Depending on the messageObj.message.
type value, it performs the desired action. If the value is camera , then it updates
the cam object with received values. The applyData function is explained in the
following code:
socket.on('serverMessage', function(content) {
applyData(content);
});
function applyData(message) {
try{
console.log(message);
var messageObj=JSON.parse(message);
if(messageObj.username!="you"){
switch(messageObj.message.type)
{
case "camera": cam.left=vec3.fromValues
(parseInt(messageObj.message.left[0]),
parseInt(messageObj.message.left[1]),
parseInt(messageObj.message.left[2]));
cam.up=vec3.fromValues(parseInt(messageObj.message.up[0]),
parseInt(messageObj.message.up[1]),
parseInt(messageObj.message.up[2]));
 
Search WWH ::




Custom Search