Search code examples
c#unity-game-enginemultiplayer

Strange Results Synchronizing Player Positions over Network


I am getting strange results when trying to sync player positions on the network. I have a network game where I spawn two players into the world. Each player has a network view with no observed object on it. Each fixed update, I make an RPC call to update the position of the player on the server. However, the position only begins to update when I move a player to the right. Any other movement will not be shown, until I begin to move the player right, in which case the position will update immediately. Here is the relevant code so far:

void FixedUpdate ()
{
    if (networkView.isMine)
    {
        grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
        anim.SetBool("ground", grounded);

        anim.SetFloat("vSpeed", rigidbody2D.velocity.y);

        float move = Input.GetAxis("Horizontal");

        anim.SetFloat("speed", Mathf.Abs(move));

        rigidbody2D.velocity = new Vector2(move * MaxSpeed, rigidbody2D.velocity.y);


        float speed = move * MaxSpeed;
        networkView.RPC("UpdateNetworkPosition", RPCMode.Others, LastPosition, speed);

    } 
}

[RPC]
void UpdateNetworkPosition(Vector3 newPosition, float speed)
{
    Debug.Log("Updating network position");
    transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * speed);
}

Thanks for any advice!


Solution

  • So it turns out the answer for this was rather simple. I was passing the speed at which the character was moving into the RPC so that I could lerp the character by the correct speed to ensure that he would move correctly over the network. However, since I used a speed determined by multiplying a speed factor by Input.GetAxis, anytime I moved left I was sending my RPC a negative speed value. Therefore, it was trying to lerp from one position to another at a speed less than zero, and thus it would not move. The problem was solved by using the absolute value for my speed factor by which to lerp.