Search Unity

Player movement using server rpc doesn't work on the client side.

Discussion in 'Netcode for GameObjects' started by EpselonZero, Jan 4, 2022.

  1. EpselonZero

    EpselonZero

    Joined:
    Dec 29, 2021
    Posts:
    10
    Hi,
    I'm trying to build a character movement, but when I press a key nothing happen on the client side and if I press a key on the server side, both player moves. I'm trying to follow the documentation about netcode for gameobject but there's not a ton of explanations.


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using Unity.Netcode;
    5.  
    6. public class PlayerScript : NetworkBehaviour
    7. {
    8.     public float speed = 5.5f;
    9.  
    10.     public NetworkVariable<Vector2> Position = new NetworkVariable<Vector2>();
    11.  
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.        
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.  
    22.         if (IsOwner)
    23.         {
    24.             SubmitPositionRequestServerRpc();
    25.         }
    26.     }
    27.  
    28.     [ServerRpc]
    29.     void SubmitPositionRequestServerRpc()
    30.     {
    31.         Move();  
    32.     }
    33.     void Move()
    34.     {
    35.         if (Input.GetKey(KeyCode.D))
    36.         {
    37.             transform.Translate(Vector2.right * Time.deltaTime * speed);
    38.             Position.Value = transform.position;
    39.         }
    40.  
    41.         if (Input.GetKey(KeyCode.A))
    42.         {
    43.             transform.Translate(Vector2.left * Time.deltaTime * speed);
    44.             Position.Value = transform.position;
    45.         }
    46.     }
    47. }
    48.  
     
  2. MrMatthias

    MrMatthias

    Joined:
    Sep 18, 2012
    Posts:
    191
    Currently the Input gets only checked on the server. You need to put the Input checks into the update method inside the IsOwner block. In there you calculate a translate vector which you pass to the ServerRpc method, which applies the translation to the transform and sets the Position variable. Then in update you set the transform position to the position variable value, so that the player also moves on the clients.
     
    scmowns likes this.