Skip to content

Instantly share code, notes, and snippets.

@ruby0x1
Created March 27, 2012 14:57
Show Gist options
  • Save ruby0x1/2216602 to your computer and use it in GitHub Desktop.
Save ruby0x1/2216602 to your computer and use it in GitHub Desktop.
Multi-player games in HTML5 : Client Side Player Class
var Player = Class.extend({
init : function( remoteConnection ) {
//The opponent we are storing is actually the socket for the player connection to socket.io
this.connection = remoteConnection || false;
//Create the mesh and set the positions for the player on screen
this.setupPaddle();
//Set up input handlers for the player
this.setupInput();
},
setupPaddle : function() {
//Create the player block
this.block = new THREE.Mesh(new THREE.CubeGeometry(50,15,6), new THREE.MeshLambertMaterial({color: 0xFFFFFF}) );
//Move the block a little closer to the camera.
this.block.position.z = 15;
//Set the Y position based on whether or not this is a local player
this.block.position.y = this.connection ? -130 : 80;
//Enable shadows
this.block.castShadow = true;
//Add to the scene
game.scene.add(this.block);
},
handleNetworkInput : function( input ) {
//Set the visual position based on the network
this.block.position.x = input.x;
},
handleLocalInput : function( ) {
//The input is stored in Game.mouse for us already,
//put the mouse in canvas space into a [-1,1] range
var percentMouseInX = -1 + ( (game.mouse.x / game.width) * 2 );
//move the paddle
this.block.position.x = percentMouseInX * 135;
//now if we are online and in a game, send the input to the server
if( game.online && game.ingame ) {
game.socket.emit( 'onClientInput' , { id : game.serverid, x : this.block.position.x });
}
},
setupInput : function() {
if(this.connection) {
//Opponent gets a network handler
this.connection.on( 'onInput', this.handleNetworkInput );
}
},
//Called from the game class each tick, so we can update.
update : function( deltatime ) {
if( !this.connection ) {
//Local player uses the mouse
this.handleLocalInput();
}
},
}); //Player class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment