using UnityEngine; using Unity.Netcode; public class PlayerController : NetworkBehaviour { [SerializeField] private float moveSpeed = 5f; [SerializeField] private float sprintMultiplier = 2f; [SerializeField] private float rotationSpeed = 100f; [SerializeField] private float doubleTapTimeThreshold = 0.3f; [SerializeField] private Animator animator; private Rigidbody rb; private void Start() { if (!IsOwner && !IsServer) return; this.rb = this.GetComponent(); } private void FixedUpdate() { if (!IsOwner) return; Debug.Log("asd from " + gameObject.name); if (IsOwnedByServer) { this.HandleMovement(); this.HandleRotation(); } else { this.SendPositionDataServerRPC(); this.SendRotationDataServerRPC(); } } private void HandleMovement() { if (!IsOwner) return; float moveX = Input.GetAxisRaw("Horizontal"); float moveZ = Input.GetAxisRaw("Vertical"); bool sprintInput = Input.GetKey(KeyCode.LeftShift); float currentMoveSpeed = moveSpeed; if (sprintInput) { currentMoveSpeed *= sprintMultiplier; animator.SetBool("isSprinting", true); } else animator.SetBool("isSprinting", false); Vector3 movement = new Vector3(moveX, 0f, moveZ).normalized * currentMoveSpeed; if (movement != Vector3.zero) { this.rb.velocity = new Vector3(movement.x, this.rb.velocity.y, movement.z); animator.SetBool("isWalking", true); } else { // Set velocity to zero to stop the Rigidbody this.rb.velocity = Vector3.zero; animator.SetBool("isWalking", false); } } private void HandleRotation() { if (!IsOwner) return; Vector3 movementDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")); if (movementDirection != Vector3.zero) { Quaternion toRotation = Quaternion.LookRotation(movementDirection * rotationSpeed); this.rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.fixedDeltaTime)); } } [ServerRpc] public void SendPositionDataServerRPC() { float moveX = Input.GetAxisRaw("Horizontal"); float moveZ = Input.GetAxisRaw("Vertical"); bool sprintInput = Input.GetKey(KeyCode.LeftShift); float currentMoveSpeed = moveSpeed; if (sprintInput) { currentMoveSpeed *= sprintMultiplier; animator.SetBool("isSprinting", true); } else animator.SetBool("isSprinting", false); Vector3 movement = new Vector3(moveX, 0f, moveZ).normalized * currentMoveSpeed; if (movement != Vector3.zero) { rb.velocity = new Vector3(movement.x, rb.velocity.y, movement.z); animator.SetBool("isWalking", true); } else { // Set velocity to zero to stop the Rigidbody rb.velocity = Vector3.zero; animator.SetBool("isWalking", false); } } [ServerRpc] public void SendRotationDataServerRPC() { Vector3 movementDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")); if (movementDirection != Vector3.zero) { Quaternion toRotation = Quaternion.LookRotation(movementDirection * rotationSpeed); rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.fixedDeltaTime)); } } }