Player positions server side or client side?

Viewed 1622

I just made a multiplayer browser implementation of the game Pong using socket.io and have a question regarding logistics of real time. Basically the player's paddle is just a colored-in div that moves up or down depending on which button they're pressing. I noticed when testing my program with two different computers using AWS that the movement was nearly perfectly synchronized but sometimes not exact. For the player that controls the paddle, the movement of their paddle is done locally, but for the person they're playing against the server continuously sends them data of whether their opponent moved up or down.

My question is should I be doing all the movement server-side? Like a user presses to go up and it sends the server a request which emits to both players that the paddle should move, or is my way where movement for your paddle being done locally fine?

My code right now looks like this:

Client-side checking if up or down button pressed and emitting move request:

paddleMove = 0; // Keep track of which direction to move
speed = 5; 
    if (paddleL.position().top > arena.position().top){ // If left paddle not at top
        if (keysPressed.up) paddleMove -= speed;
    }
    if (paddleL.position().top+paddleL.height() < arena.position().top + arena.height() - 15){ // If left paddle not at bottom
        if (keysPressed.down) paddleMove += speed;
    }
    paddleL.css({  // Move paddle locally
        top: paddleL.cssNumber('top') + paddleMove + 'px'
    });
    socket.emit("moveReq", paddleMove); // Send to server 

The above code is in an interval that runs every fraction of a second.

Then the server side looks like this:

socket.on('moveReq', function(data){   // Send to opponent that other paddle moved
    socket.broadcast.emit("movePaddle", data);
});

Which in turn alerts another portion of the user-side code to move the other paddle:

socket.on("movePaddle", function(data){

        var paddleMove = 0;
        paddleMove += data; // Data is speed (direction) of movement
        paddleR.css({ // Move right paddle
            top: paddleR.cssNumber('top') + paddleMove + 'px'
        });

As I said, the movement right now is pretty good but not perfect. Should I make none of the movement local and make it all on a server emit?

2 Answers
Related