I'm creating a simple multiplayer game(server authoritative) and I need to be able to send to all players all players positions
So whenever one of the player moves I do this
private void SendPositions()
{
foreach (var item in ActiveUser.activeUsers)
{
foreach (var i in ActiveUser.activeUsers)
{
Net_OnMovement om = new Net_OnMovement();
ActiveUser user = i.Value;
om.username = user.username;
Debug.Log(om.username);
om.x = user.position[0];
om.y = user.position[1];
SendClient(item.Value.channelId, item.Value.connId, om);
}
}
}
First of all I update the players position and then send all positions to all players(here you can see only the send all to all part) And on the client side when the username is equal to username of the client I move the user else I move the "otherPlayer(s)" Works perfectly when there's only one player but after connecting the other one everything is delayed a lot and unresponsive. Is there something wrong with this way of sending data? Or should I look for the error elsewhere
EDIT
*player actually starts moving immediately after pressing button but the movement is laggy and it keeps moving long after the button is released (the longer I hold the longer it keeps moving after) - which actually means that the server can't handle the pace I guess ?
It depends on your testing environment, but if it isn't on a local network then what you are experiencing is simple network delay. Communication isn't instantaneous and can take more or less time depending on your connection and distance to the server.
What's happening is that as a player, you are transmitting the order to move to the server and you have to wait for the server to reply back the updated position to actually see yourself move. If there's a 50ms delay with the server (which is an alrightish value), then you'll have to wait 100ms to see the position being updated (6 frames at 60fps) resulting in the laggy feeling.
This is a very well known problem and there's multiple solutions to it. The most common one in fast paced games is known as Client side prediction and Server Reconciliation. Basically, you make the player move immediately Client side as you receive the input, so that there's no laggy feeling (that's Client side prediction). But since your server still has the authority and you are ahead on the server, your player will be put back at the position where the server thought you were which will create choppy movements client side. To prevent this, you have to check when receiving server update if the player position given by the player was predicted client side, and if so, not force back the player to that position (that's server reconciliation).
I highly recommend your read this guide to get a better understanding of network issues with Client-Server architecture.