I've searched for quiet some time now around the web for a solution to my problem, and couldn't find any sufficient enough resource to help me.
I'm developing a co-op RPG game in Unity 3D, using the UDP library https://github.com/RevenantX/LiteNetLib , and I managed to do a client-server connection, where I send vector of my player movement (time calculation is not applied- so the server can handle it on its own tick) to the server, and it calculates the new position where the character should be, and afterwards I broadcast to all players the new same vector that I sent to the server so they can also calculate the physics by themselves.
The problem I'm running into is that the movement seems very laggy and sometimes miscalculated.
I'm not sure if its due to my local PlayerController script or due to bad network, or bad design where I should actually send the new absolute position of the client.
I know this is a hard question, I am hoping for some guidelines or expertise of developers who tried to create multiplayer games themselves,
I should also note, that cheating doesn't concern me because it is a coop game and not a competitive one.
Thanks in advance for any help.
Here is a snippet of my local PlayerController code:
void Update()
{
// Get Input for axis
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
// Calculate the forward vector
Vector3 camForward_Dir = Vector3.Scale(UnityEngine.Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
Vector3 move = v * camForward_Dir + h * UnityEngine.Camera.main.transform.right;
if (move.magnitude > 1f) move.Normalize();
// Calculate the rotation for the player
move = transform.InverseTransformDirection(move);
// Get Euler angles
float turnAmount = Mathf.Atan2(move.x, move.z);
transform.Rotate(0, turnAmount * RotationSpeed * Time.deltaTime, 0);
if (_characterController.isGrounded)
{
_moveDir = transform.forward * move.magnitude;
_moveDir *= Speed;
}
_moveDir.y -= Gravity * Time.deltaTime;
var delta = _moveDir * Time.deltaTime;
_characterController.Move(delta);
if (!IsMoving())
{
//_wasMoving = false;
return;
}
// we send the move direction so that the server and other client`s can calculate for themselves
OnPlayerMoved?.Invoke(_moveDir, Time.deltaTime);
}
As I mentioned in my comment, people who still need help with this topic might want to view this demo https://github.com/RevenantX/NetGameExample it demonstrates how to create 2D player sync which can easily be applied for 3D, the code belongs to RevenantX, and it relies on a UDP library which he also created for the community.