80 lines
2.5 KiB
C#
80 lines
2.5 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;
|
|
|
|
[Header("External impulses")]
|
|
[SerializeField, Min(0.1f)] private float impulseDamping = 9f;
|
|
|
|
private CharacterController characterController;
|
|
private Vector3 verticalVelocity;
|
|
private Vector3 externalImpulseVelocity;
|
|
private bool isInitialized;
|
|
|
|
public Vector3 ExternalImpulseVelocity => externalImpulseVelocity;
|
|
|
|
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);
|
|
}
|
|
|
|
public void AddImpulse(Vector3 velocityChange)
|
|
{
|
|
if (!isInitialized || !IsOwner)
|
|
return;
|
|
|
|
externalImpulseVelocity += velocityChange;
|
|
}
|
|
|
|
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 + externalImpulseVelocity) *
|
|
Time.deltaTime);
|
|
externalImpulseVelocity = Vector3.MoveTowards(
|
|
externalImpulseVelocity,
|
|
Vector3.zero,
|
|
impulseDamping * Time.deltaTime);
|
|
}
|
|
}
|