- Home /
How do I smoothly sync players position over the network in Unity3D(UNet) without bugs?
I have a prefab with a character controller attached. The movement works great locally, but when I try to sync it with a Network Transform, it's very laggy. So I tryed it with a script:
void Update(){
if (isLocalPlayer) {
if (cc.isGrounded) {
oldMd = moveDirection;
moveDirection = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
moveDirection = cc.transform.TransformDirection (moveDirection);
moveDirection *= currentSpeed;
if (Input.GetButton ("Jump")) {
moveDirection.y = jumpSpeed;
}
}
if(oldMd.x!=moveDirection.x&&oldMd.z!=moveDirection.z){
CmdMove (moveDirection, gravity);
}
}
////moveDirection.y -= gravity * Time.deltaTime;
//cc.Move (moveDirection * Time.deltaTime);
if ((w || a || s || d) && !sprint) {
currentSpeed = walkSpeed;
} else if (sprint) {
currentSpeed = sprintSpeed;
} else {
currentSpeed = 0;
}
if(!isLocalPlayer)
UpdateClientsPos();
}
[ClientRpc]
public void RpcSyncedPos(Vector3 syncedPos, Quaternion syncedRotation)
{
transform.position = syncedPos;
transform.rotation = syncedRotation;
}
[Server]
private void UpdateClientsPos()
{
RpcSyncedPos(transform.position, transform.rotation);
}
void FixedUpdate(){
moveDirection.y -= gravity * Time.fixedDeltaTime;
cc.Move (moveDirection * Time.fixedDeltaTime);
}
[ClientRpc]
public void RpcMove(Vector3 moveDirection_, float gravity_){
moveDirection = moveDirection_;
gravity = gravity_;
}
[Command]
private void CmdMove(Vector3 moveDirection_, Vector3 gravity_){
RpcMove(moveDirection_, gravity_);
}
At the first sight it seems to work nice and smoothly, but there is a bug. If I go around the corner of a house, carefully, and I am touching the collider, then one player sees the player goes around the corner and the other player is still walking against the collider and didn't go around the corner. So actually I could walk out of the world, while the other player sees me walking against a wall. Do you get me? Does someone have a better code to sync position over the network? Sorry for my bad English I am 15 years old and Dutch.
Your answer
Follow this Question
Related Questions
Unity networking tutorial? 6 Answers
Unet assigning local player Authority to a gameObject. 1 Answer
How can I assign every connecting player to one of two teams, so that both teams are balanced? 2 Answers
How to connect to hosted scene (Multiplayer) 2 Answers
How to sync the position and rotation of a player controlled object over network? 0 Answers