29 lines
1.1 KiB
C#
29 lines
1.1 KiB
C#
using Unity.Netcode;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
public sealed class PlayerMovementController : NetworkBehaviour, IPlayerSystem
|
|
{
|
|
[SerializeField, Min(0.1f)] private float movementSpeed = 4.5f;
|
|
private bool isInitialized;
|
|
|
|
public void Initialize(PlayerFacade facade) => isInitialized = true;
|
|
|
|
private void Update()
|
|
{
|
|
if (!isInitialized || !IsOwner || Keyboard.current == null) return;
|
|
Vector2 input = new(
|
|
(Keyboard.current.dKey.isPressed ? 1 : 0) - (Keyboard.current.aKey.isPressed ? 1 : 0),
|
|
(Keyboard.current.wKey.isPressed ? 1 : 0) - (Keyboard.current.sKey.isPressed ? 1 : 0));
|
|
if (IsServer) Move(input); else MoveServerRpc(input);
|
|
}
|
|
|
|
[ServerRpc] private void MoveServerRpc(Vector2 input) => Move(input);
|
|
private void Move(Vector2 input)
|
|
{
|
|
if (input.sqrMagnitude > 1) input.Normalize();
|
|
Vector3 direction = new(input.x, 0, input.y);
|
|
transform.position += direction * (movementSpeed * Time.deltaTime);
|
|
if (direction.sqrMagnitude > 0.001f) transform.forward = direction;
|
|
}
|
|
} |