Search Unity

Netcode for gameobjects server authoritative movement

Discussion in 'Netcode for GameObjects' started by PedroPaulo95, Oct 12, 2022.

  1. PedroPaulo95

    PedroPaulo95

    Joined:
    Apr 22, 2020
    Posts:
    6
    I'm having trouble understanding Netcode for gameobjects.
    Could someone show me what authoritative code on the server would look like (without using ClientNetworkTransform for movement) to move and sync between all clients? If possible, could you explain to me how it works?
    I've looked for explanations and videos, but most of them use ClientNetworkTransform, and for those that use the server I couldn't understand the explanation.

    My current code is below. That way, only the Host is moving, the clients don't move.

    Thanks!

    Code (CSharp):
    1. public class PlayerNetwork : NetworkBehaviour
    2. {
    3.     public float speed = 3.5f;
    4.     public Vector2 defaultPositionRange = new Vector2(-4, 4);
    5.  
    6.     private void Start()
    7.     {
    8.         transform.position = new Vector3(Random.Range(defaultPositionRange.x, defaultPositionRange.y), 1, Random.Range(defaultPositionRange.x, defaultPositionRange.y));
    9.     }
    10.  
    11.     void Update()
    12.     {
    13.         if (IsOwner)
    14.             Move();
    15.     }
    16.  
    17.     public void Move()
    18.     {
    19.         var deltaX = 0;
    20.         var deltaZ = 0;
    21.  
    22.         if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
    23.             deltaZ += 1;
    24.  
    25.         if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
    26.             deltaX -= 1;
    27.  
    28.         if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
    29.             deltaX += 1;
    30.  
    31.         if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
    32.             deltaZ -= 1;
    33.  
    34.         if (deltaX != 0 || deltaZ != 0)
    35.         {
    36.             var newMovement = new Vector3(deltaX, 0, deltaZ);
    37.             transform.position = Vector3.MoveTowards(transform.position, transform.position + newMovement, speed * Time.deltaTime);
    38.         }
    39.     }
     
  2. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    I already sort of answered this in another post you made, but...

    Instead of setting the transform.position (which only the server is allowed to do if you're not using ClientNetworkTransforms), you call a ServerRpc in that line, say
    MovePlayerServerRpc(deltaX,deltaZ);
    That function could look like this:

    Code (CSharp):
    1. [ServerRpc]
    2. private void MovePlayerServerRpc(int deltaX,int deltaZ) {
    3.     transform.position=Vector3.MoveTowards(transform.position,transform.position+new Vector3(deltaX,0,deltaZ),speed*Time.deltaTime);
    4. } //MovePlayerServerRpc
     
    wmcnamara, CodeSmile and PedroPaulo95 like this.