How to make an online multiplayer game




















Run the server again using the command node server. If you were making a real game, it would be a much better idea to refactor a lot of the code used in this demonstration into their own files. These multiplayer games are pretty good examples of MVC architecture. All the game logic should be handled on the server, and the only thing the client should do is send user input to the server and render the information the server sends.

There are a few flaws with this demo project though. The game updating is tied to the socket listener. If I wanted to mess with the game state, I could type the following into the inspector:.

Depending on the computer, movement data is now being sent to the server much more than 60 times a second, causing the player to start moving insanely fast. This leads me to another point known as the concept of authoritative server determination. At no point should the client have control over any data on the server. A clever player was able to exploit this by injecting a line of JavaScript very similar to the one above to gain near-infinite shooting speed. The best analogy I can draw is that the clients should only send intents to the server, which are then processed and used to modify the state of the players if they are valid.

Ideally, the update loop on both the client and the server should be independent of the sockets. Try not to have your game update inside of a socket. Rather, you should do something like this:. This is a lot clunkier, but will guarantee smoother and more consistent behavior by calculating the time between the last update and the current time to figure out the proper distance to move the player. Fork the demo project and try to implement the code above. Put some functionality into and try to make a full-fledged game.

Another thing to implement might be removing disconnected players. If you want to try this, I highly recommend reading The Nature of Code , since it provides a lot of useful insight. The hardest part about creating multiplayer browser games is the networking. Say you have 64 players in close proximity to each other.

Each chunk of data player movements, game updates, etc needs to be broadcast to each player. So if you only had 2 players, you would need 1 chunk of data per frame per player so 2 chunks per frame.

Now you start increasing your amount of players. Now keep scaling up, and you get the picture. Eventually, your servers going to get choked up, either due to bandwidth limitations, or poor network code. MovePosition rigidbody. S rigidbody. D rigidbody. A rigidbody. This will enable us to send data packages over the network to synchronize the player. This means that synchronized data will be sent automatically, but only if its value changed.

So for example if you move as a player, your position will be updated on the server. Add the player object to the hierarchy to make it a prefab, so we can instantiate it on the network. In the NetworkManager-script add a public game object variable for the player prefab. In the new function SpawnPlayer , the prefab will be instantiated on the network, so all clients will see this object within their game. It requires a position, rotation and group, so I would suggest creating a spawn point.

Instantiate playerPrefab, new Vector3 0f, 5f, 0f , Quaternion. Time for another test! Create a new build and run two instances again. You will notice that you can control all players connected, not just your own. This shows one important aspect that will be used often when creating a multiplayer game: who controls what object? One way to fix this problem is to build in a check on the player code so it only receives input from the user that instantiated the object. Because we set reliable synchronization on the network view, data is sent automatically across the network and no other information is required.

Add the following if-statement to the Update :. Another solution could be to send all input to the server, which will then convert your data to actual movement and send back your new position to everyone on the network. The advantage is that everything is synchronized on the server.

This prevents players from cheating on their local client. A disadvantage of this method is the latency between the client and server, which may result in the user having to wait to see the actions he performed. There are two methods of network communication. The first is State Synchronization and the other is Remote Procedure Calls, which will be covered in another paragraph.

State Synchronization constantly updates values over the network. This approach is useful for data that changes often, like player movement. In the function OnSerializeNetworkView the variables are sent or received and will synchronize them quick and simple.

The observed field contains the component that will be synchronized. The transform is automatically added to this field, which results in the position, rotation and scale being updated depending on the sendrate.

Drag the component of the player script in the observed field so we can write our own synchronization method. Add OnSerializeNetworkView to the player script. This function is automatically called every time it either sends or receives data.

If the user is writing to the stream, it means he is sending the data. By using stream. Serialize the variable will be serialized and received by other clients. If the user receives the data, the same serialization-function is called and can now be set to store the data locally. Note that the order of variables should be the same for sending and receiving data, otherwise the values will be mixed up.

Serialize ref syncPosition ; rigidbody. Make another build and run it. The results should be the same as before, but now we have granted ourselves control over the movement and how the synchronization works. You might have noticed latency issues between the two instances due to the sendrate. The standard settings in Unity is that a package is being tried to send 15 times per second.

For testing purposes, we will change the sendrate. Then, change the sendrate to 5, resulting is less data packages being sent. If you would do another build and test, the latency should be clearer. To smooth the transition from the old to the new data values and fix these latency issues, interpolation can be used.

There are several options how this can be implemented. For this tutorial, we will interpolate between the current position and the new position received after synchronization.

OnSerializeNetworkView needs to be extended with to store all the required data: the current position, new position and delay between updates. Serialize ref syncPosition ;. We had a check in Update whether the object is controlled by the player. We need to add the functionality that when this is not the case, we will use interpolation between the synchronized values.

Though the transitions look smooth, you notice a small delay between the input and the actual movement. This is because the position is updated after the new data is received. Until we invent time travel, all we can do is predict what is going to happen based on the old data.

One method to predict the next position is by taking the velocity into account. A more accurate end position can be calculated by adding the velocity multiplied by the delay. Serialize ref syncPosition ; stream. Serialize ref syncVelocity ;. After building and testing the game again, you will notice the transitions are still smooth and the latency between your input and the actual movement seem less.

There are also a few corner-cases where behaviour might seem a little strange if the latency is too high.

If the player starts moving, the other clients still predict you would stand still. Set the sendrate at network settings back to 15 updates per second for better results. For our Kickstarter demo, we used a navmesh to walk around and this seemed to make interpolation and prediction better. The sendrate was set to 5 and as a user you could barely notice the delay. This tutorial will not go any deeper into the integration of the navmesh, but for your future projects it might be worth to consider this approach.

Another method of network communication is Remote Procedure Calls RPCs , which is more useful for data that does not constantly change.

A good example what we used these for in our Kickstarter demo is dialog. In this paragraph we will change the color of a player over the network. By adding [RPC] in front of the function, it can be called over the network. This approach is only able to send integers, floats, strings, networkViewIDs, vectors and quaternions.

So not all parameters can be sent, but this can be solved. To send a game object, we should add a network view component to this object so we can use its networkViewID. To send a color, we should convert it to a vector or quaternion. An RPC is sent by calling networkView. RPC , in which you define the function name and parameters. The last two also have the functionality to set is as buffered, this results in newly connected players receiving all these buffered values.

Because we send this data package every frame now, there is no need to buffer it. To integrate this functionality to our tutorial game, Update needs to call the function to check for input and change the material to a random color. The RPC function changes the color based on the input and if the player object is controlled by the user, he will send an RPC to all others on the network.

GetKeyDown KeyCode. Range 0f, 1f , Random. I hope this tutorial was a good introduction to implement networking to a Unity game. The subjects we have addressed are:. You can download the entire project here.

Houden jullie vast aan UnityNetworking voor de game? Je krijgt veel problemen met spelers die niet met elkaar kunnen verbinden. Hoi Mike, bedankt voor je suggestie. Dat gaan we nog zeker onderzoeken. Voor nu hebben we gekozen voor UnityNetworking vanwege de kleine schaal van de demo. Ok cool, makes sense. Hey, this is a great example and tutorial on how to start with multiplayer games, since it covers most of the basic things needed to understand a networked game.

Yes having such things as a much more efficient system comes with the cost of having to code more things, and while all this can be a class that is very easily maintainable it is well worth the effort. Not only will you be able to run more instances of your games on the same hardware and will be less taxing on processing power and bandwidth usage.

Which, if you want to host your servers on the cloud, can reduce a lot of costs and make all your infrastructure smaller and less complicated. Not only will this help in performance but will make most changes very easy to maintain and update to production since you control the server hosts. Btw, if you would like to check many more optimizations on multiplayer games, you can check my blog.

Very nice Tutorial. However for all other people trying this tutorial. There is one thing that has been forgotten once you try to run a server and client on the same computer.

Any idea why? Are you sure the setting is saved in the project? It might be best to go to the Unity forums and report it there. Good luck! Has anyone on here actually used this method? Anyone know how to fix this? Simply check the one argument that is received by that event to see if it equals MasterServerEvent.

I am having an issue with this tutorial. I have worked out that it is because the observed network view is set to the player position whereas in the downloaded example file it is set to a C script how do I fix this?

This is set automatically and does not require code to update the position. To do this, first add the C script to the player object, so the component appears in the inspector.

Now you are able to drag this component into the observed-field overwriting the transform. Thanks for writing it! Great to hear this post was able to help you. Sorry for not adding the importance of ordering variables during synchronization. Hi Maddy, the download works for me. Maybe you can try again with another web browser or something.

Hey nice tutorial, although i am having an issue with connecting both instances to the server. Hello jens,would youike to make an online multiplayer game with me and a few other people please contact me at my e-mail: ahmetcelaltopra gmail. This was really helpful for me- I learned how easy networking actually is!

Thanks for the tips. Hi Francis. That would be a great extension to the post. Contact me at stein paladinstudios. There is a typo error at Prediction line At what point in the tutorial are you?



0コメント

  • 1000 / 1000