Search Unity

Objects' movements aren't synchronized perfectly

Discussion in 'Netcode for GameObjects' started by Donkrokodil, Jan 22, 2023.

  1. Donkrokodil

    Donkrokodil

    Joined:
    Aug 16, 2019
    Posts:
    9
    Hi, I have the following problem with physics in Unity Netcode.

    Suppose that one client starts moving his object (using rigidbody2d.Addforce). However, another client observes this movement ~0.5-1 seconds later than this object actually moves. How to solve this problem with time delay (P.S. I'm relatively new in unity coding)?

    public enum State { up, down, left, right, no }
    State realstate = State.no;
    float speed = 70f;
    void Update()
    {
    if (IsLocalPlayer)
    {

    {
    if (Input.GetKeyDown(KeyCode.W))
    {
    realstate = State.up;
    }
    if (Input.GetKeyDown(KeyCode.S))
    {
    realstate = State.down;
    }
    if (Input.GetKeyDown(KeyCode.D))
    {
    realstate = State.right;
    }
    if (Input.GetKeyDown(KeyCode.A))
    {
    realstate = State.left;
    }
    if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.D) || Input.GetKeyUp(KeyCode.A))
    {
    realstate = State.no;
    }
    }
    }
    }
    void FixedUpdate()
    {
    if (GetComponent<Rigidbody2D>().velocity.magnitude == 0)
    {
    if (realstate == State.up)
    {
    transform.localRotation = Quaternion.Euler(0, 0, 0);
    GetComponent<Rigidbody2D>().AddForce(transform.up * speed, ForceMode2D.Force);
    }
    if (realstate == State.down)
    {
    transform.localRotation = Quaternion.Euler(0, 0, 180);
    GetComponent<Rigidbody2D>().AddForce(transform.up * speed, ForceMode2D.Force);
    }
    if (realstate == State.right)
    {
    transform.localRotation = Quaternion.Euler(0, 0, 270);
    GetComponent<Rigidbody2D>().AddForce(transform.up * speed, ForceMode2D.Force);
    }
    if (realstate == State.left)
    {
    transform.localRotation = Quaternion.Euler(0, 0, 90);
    GetComponent<Rigidbody2D>().AddForce(transform.up * speed, ForceMode2D.Force);
    }

    }
    else
    {
    if (realstate == State.no)
    {
    GetComponent<Rigidbody2D>().Sleep();
    }
    }
    }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,491
    FYI: Here's how to post code on the forum.
     
  3. RikuTheFuffs-U

    RikuTheFuffs-U

    Unity Technologies

    Joined:
    Feb 20, 2020
    Posts:
    440
    Hi @Donkrokodil , what you need is Client side prediction + Reconciliation (or a client-driven variant of it). This is not available in Netcode For GameObjects out of the box, but if you google it you'll be able to find several relevant articles on how to implement it for you specific use case. (here's an example video)

    Hope this helps ^.^