title: Multiplayer game movement synchronization
body: <p>I'm working on a multiplayer game and i'm having problem with synchronizing players.</p>
  
  <p>When a player presses one of the move keys (W,A,S,D) then the client sends a packet about the pressed button, the server sets the velocity according to the pressed key and sends back to all nearby players the new velocity.</p>
  
  <p>When the player release the key then the clients sends a packet, server sets the player velocity to 0,0 and sends the position and velocity to all nearby players.</p>
  
  <p>So the problem is when i release the key, then most of the time the player jumps back.</p>
  
  <p>How could i fix this?</p>
  
  <p>i'm using socket.io.</p>
  
  <p>Client side:</p>
  
  <pre><code>   socket.on('positionEntity', function (data) {
          console.log((data.x - entities[data.id].x)+" "+(data.y - entities[data.id].y));
          entities[data.id].setPosition(data);
      });
  
      $(document).keyup(function(e) {
          if (e.keyCode == 87) {
              keys.W = false;
              socket.emit("stopMove", {dir: 0, time: Date.now()});
          }
  
          if (e.keyCode == 65) {
              keys.A = false;
              socket.emit("stopMove", {dir: 1, time: Date.now()});
          }
  
          if (e.keyCode == 83) {
              keys.S = false;
              socket.emit("stopMove", {dir: 2, time: Date.now()});
          }
  
          if (e.keyCode == 68) {
              keys.D = false;
              socket.emit("stopMove", {dir: 3, time: Date.now()});
          }
      });
  
      $(document).keydown(function(e) {
          if (e.keyCode == 87 &amp;&amp; !keys.W) {
              keys.W = true;
              socket.emit("startMove", {dir: 0, time: Date.now()});
          }
  
          if (e.keyCode == 65 &amp;&amp; !keys.A) {
              keys.A = true;
              socket.emit("startMove", {dir: 1, time: Date.now()});
          }
  
          if (e.keyCode == 83 &amp;&amp; !keys.S) {
              keys.S = true;
              socket.emit("startMove", {dir: 2, time: Date.now()});
          }
  
          if (e.keyCode == 68 &amp;&amp; !keys.D) {
              keys.D = true;
              socket.emit("startMove", {dir: 3, time: Date.now()});
          }
      });
  </code></pre>
  
  <p>Server side:</p>
  
  <pre><code>socket.on('startMove', function(data) {
      if (data.dir == 0) socket.player.setMotionY(-5);
      if (data.dir == 1) socket.player.setMotionX(-5);    
      if (data.dir == 2) socket.player.setMotionY(5);
      if (data.dir == 3) socket.player.setMotionX(5);
  
      io.sockets.emit("positionEntity", socket.player.serializePosition());
  });
  
  socket.on('stopMove', function(dir) {
      socket.player.setMotionX(0);
      socket.player.setMotionY(0);
  
      io.sockets.emit("positionEntity", socket.player.serializePosition());
  });
  </code></pre>