When I test my game without relay , character movements work properly, but when test with relay, other players character movements do not work properly. What is the reason?
this is my movement code
using System.Collections;
using UnityEngine;
using TMPro;
using Random = UnityEngine.Random;
using Unity.Netcode;
using UnityEngine.SceneManagement;
public class Movement : NetworkBehaviour
{
private Rigidbody2D rb;
private Animator anim;
[SerializeField] private float Speed;
[SerializeField] private float JumpForce;
[SerializeField] private bool Ice;
private float move;
private enum MovementState { idle, runing, falling, jumping, Death}
[SerializeField] private LayerMask JumpableGround;
public bool CanMove = false;
public bool CanTakeDamage = false;
private NetworkVariable<Vector2> NewVelocity = new NetworkVariable<Vector2>();
private void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
NewVelocity.Value = rb.velocity;
CanMove = true;
CanTakeDamage = true;
}
private void Update()
{
if (IsOwner)
{
if (CanMove)
{
move = Input.GetAxisRaw("Horizontal");
if (Ice)
rb.AddForce(new Vector2(move * Speed, rb.velocity.y));
else
rb.velocity = new Vector2(move * Speed, rb.velocity.y);
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
{
if (IsGrounded())
{
if (Ice)
rb.velocity = new Vector2(rb.velocity.x, JumpForce / 2);
else
rb.velocity = new Vector2(rb.velocity.x, JumpForce);
}
}
UpdatePositionServerRpc(rb.velocity);
}
}
else
{
rb.velocity = NewVelocity.Value;
}
UpdateAnim();
}
[ServerRpc]
private void UpdatePositionServerRpc(Vector2 newValue)
{
NewVelocity.Value = newValue;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ice"))
{
Ice = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("ice"))
{
Ice = false;
}
}
private bool IsGrounded()
{
return Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, 0.05f, JumpableGround);
}
private void UpdateAnim()
{
if(CanMove)
{
MovementState state;
if (rb.velocity.x > 0.1f)
{
state = MovementState.runing;
sprite.flipX = false;
}
else if (rb.velocity.x < -0.1f)
{
state = MovementState.runing;
sprite.flipX = true;
}
else
{
state = MovementState.idle;
}
if (rb.velocity.y > 0.1f)
{
state = MovementState.jumping;
}
else if (rb.velocity.y < -0.1f)
{
state = MovementState.falling;
}
anim.SetInteger("State", (int)state);
}
}
}