I'm currently building my own netcode for a Unity game (for learning experience) and I'm running into some serious delay on the "decoding packets" side of things.
Basically, I have playerObject
's that send their position data (Vector3(x,y,z)) as a JSON string to the server, and the server sends that back out to all other players.
The socket side of things are moving along nicely. Very little delay from when a packet is created to when a packet is received.
But I am getting a massive delay on my Clients when they are trying to un-JSON the remote client's position:
Vector3 remotePos = JsonUtility.FromJson<Vector3>(_command.Substring(5 + _usernameLength));
the Json string has an identifier at beginning of the string to say that it is a Position update, followed by two numbers signifying the length of the username, then the username (so that the remote clients can update the proper playerObject
. The whole string will look something like this.
POS09NewPlayer{"x":140.47999572753907,"y":0.25,"z":140.7100067138672}
After receiving such a packet from the server, my clients will preform the following task:
int _usernameLength = Int32.Parse(_command.Substring(3, 2));
string _username = _command.Substring(5, _usernameLength);
Vector3 remotePos = JsonUtility.FromJson<Vector3>
if (_username != username)
{
playerDict[_username].transform.position = remotePos;
}
All of this "works", but gets very sluggish after just 3 clients connect simultaneously.
What am I doing wrong? There must be a significant flaw as I am only sending updates every .015 seconds for 3 players, where as games like Battlefield can send 60 updates a second for 64 players!
Any advice would be appreciated.
Well, there is certainly room for optimization. Since you are quoting big game engines as a reference, I will give you some examples based on the older Unreal Engine versions and some of the optimizations they are using:
The whole matter is a lot more complex than what little I can cram into this post, but the gist of it is probably: network bandwidth is the most limited resource in multiplayer games, so the engine goes out of its way to send as little and few information packages as it can get away with.
Notice something? Less than a single component of your position vector would already be considered way too large for the entire vector in this engine. I guess JSON really introduces some overhead here, simply due to its verbosity. You are sending numbers as strings when you could also be just sending their actual bits and infer their meaning from the actual package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With