Node.js/Nowjs - Moving a sprite and keeping track of time server-side

519 views Asked by At

I am using node.js and express, and I am calling server-side functions and syncing variables using nowjs. Suppose the user is drawn as a sprite on the canvas. His x,y coordinates are kept server-side in a "position" array.

Server-side:

position = { x : 0; y : 0 } 

updatePosition = function (a,b) 
{ 
  playerPosition.x += a; 
  playerPosition.y += b; 
} 

Client-side:

if keypress('right'){ updatePosition(32,0); }

These are pseudocode. When the user presses the 'right' button, the server-side "updatePosition" function is called, which adds 32 (pixels) to the x-coordinate of the "position" array. This array is then shared with the client, and the new position is drawn on the canvas using client-side function.

Suppose I don't want to draw the sprite at the new position instantly. I want to play a walking animation that gradually moves the sprite 32 pixels to the right, and takes say 1 second to complete. I might implement it this way:

  1. User presses the 'right' button.
  2. The animation starts playing client-side.
  3. updatePosition is called server-side as usual.
  4. When animation on the client finishes, check if the final position client-side matches the coordinates stored server side.

When the user presses the 'right' button/key, he cannot repeat the keypress until 1 second later. The 1 second long "walking" animation has to complete and final position checked with the server-side coordinates before he can press 'right' again to move his sprite.

Question: How do I keep track of the 1 second server side? I can't do it client-side because the user will be able to hack his client to reduce the animation time.

Is the solution to "timestamp" the position array? E.g. position = { x : 0; y : 0, time: 0 }. If the user presses the 'right' button again, the server would check to see if the last position update was greater than 1 second ago. If less than 1 second, the server ignores it.

1

There are 1 answers

5
Pierre On BEST ANSWER

Why not simply storing a "lock" in the user session?

session.editLock = new Date().getTime();

When another edit is triggered by the client, just:

if(session.editLock && new Date().getTime() - session.editLock > 1000) {
  // Return error
}

Modifying the position object doesn't feel right to me. A position object is meant to store position, not time.