Fast-Paced Multiplayer: Sample Code and Live Demo
35 |Part I - Part II - Part III - Part IV - Live Demo
37 | 43 | 44 |This is a sample implementation of a client-server architecture demonstrating the main concepts explained in my Fast-Paced Multiplayer series of articles (except for Entity Interpolation, which I haven’t done yet). It won’t make much sense unless you’ve read the articles first.
45 |The code is pure JavaScript and it’s fully contained in this page. It’s less than 400 lines of code, including a lot of comments, demonstrating that once you really understand the concepts, implementing them is relatively straightforward.
46 |Player View
47 |Lag =ms · Prediction · Reconciliation
48 | 49 | 50 |Non-acknowledged inputs: 1
51 |Server View
52 |Update times per second
53 | 54 |55 | 468 | 469 |
Guided Tour
470 |The two views show what the player sees, and the state of the world according to the server. You can control the green ball using the right and left arrow keys. Give it a try!
471 |The ideal case
472 |Start with Lag = 0 and Update = 60. This is an ideal case: the Server processes the world state as fast as the client produces it, and there’s no delay whatsoever between the Client and the Server. Of course, it works perfectly.
473 |Slow server
474 |Now set Update = 5. The Server now sends only 5 updates per second, so the animation on the Client side looks choppy. But the whole thing still feels somewhat responsive.
475 |Laaaaaaaaaaaaaaaaaag
476 |Let’s add some Lag - set it to 250 ms. The game doesn’t feel so responsive anymore; the player’s view is not updated until the Server has acknowledged the inputs sent by the Client. Because of the two-way lag, the character starts moving half a second after you press the key.
477 |Client-Side Prediction
478 |Enable Prediction and lower Update to 1. Keep the right key pressed for a while. Now the animation feels very smooth, because it’s predicted on the Client. But whenever the Server finally gets around to processing all the client inputs, the state it sends back is delayed respect to the player’s prediction because of the lag, so the Player jumps back.
479 |Server Reconciliation
480 |Now enable Reconciliation. Whenever the Server sends its state, we take all the not-yet-acknowledged inputs and redo the prediction, starting from the authoritative position sent by the Server. No matter how much lag you add or how infrequent the server udpates are, the Client is always in sync!
481 |