60 lines
1.9 KiB
C#
60 lines
1.9 KiB
C#
using Unity.Netcode;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
|
|
[RequireComponent(typeof(CharacterController))]
|
|
public sealed class PlayerController : NetworkBehaviour, IPlayerSystem
|
|
{
|
|
[Header("Movement")]
|
|
[SerializeField, Min(0.1f)] private float walkSpeed = 4.5f;
|
|
[SerializeField, Min(0.1f)] private float sprintSpeed = 7f;
|
|
|
|
[Header("Vertical movement")]
|
|
[SerializeField, Min(0.1f)] private float jumpHeight = 1.4f;
|
|
[SerializeField, Min(0.1f)] private float gravity = 20f;
|
|
|
|
private CharacterController characterController;
|
|
private Vector3 verticalVelocity;
|
|
private bool isInitialized;
|
|
|
|
public void Initialize(PlayerFacade facade)
|
|
{
|
|
characterController = GetComponent<CharacterController>();
|
|
isInitialized = characterController != null;
|
|
}
|
|
|
|
public void SubmitMovement(Vector2 moveInput, bool wantsToSprint, bool wantsToJump)
|
|
{
|
|
if (!isInitialized || !IsOwner)
|
|
return;
|
|
|
|
SimulateMovement(moveInput, wantsToSprint, wantsToJump);
|
|
}
|
|
|
|
public void SubmitYaw(float yawDelta)
|
|
{
|
|
if (!isInitialized || !IsOwner)
|
|
return;
|
|
|
|
transform.Rotate(0f, yawDelta, 0f, Space.Self);
|
|
}
|
|
|
|
private void SimulateMovement(Vector2 moveInput, bool wantsToSprint, bool wantsToJump)
|
|
{
|
|
if (moveInput.sqrMagnitude > 1f)
|
|
moveInput.Normalize();
|
|
|
|
if (characterController.isGrounded && verticalVelocity.y < 0f)
|
|
verticalVelocity.y = -2f;
|
|
|
|
if (wantsToJump && characterController.isGrounded)
|
|
verticalVelocity.y = Mathf.Sqrt(jumpHeight * 2f * gravity);
|
|
|
|
verticalVelocity.y -= gravity * Time.deltaTime;
|
|
|
|
float speed = wantsToSprint ? sprintSpeed : walkSpeed;
|
|
Vector3 horizontalDirection = transform.right * moveInput.x + transform.forward * moveInput.y;
|
|
characterController.Move((horizontalDirection * speed + verticalVelocity) * Time.deltaTime);
|
|
}
|
|
}
|