Files
ProjectMD/Assets/Scripts/Player/PlayerMovement.cs

74 lines
2.2 KiB
C#

using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement Settings")]
public float moveSpeed = 5f;
public float jumpHeight = 1.5f; // 점프 높이
public float gravity = -19.62f; // 기본 중력보다 약간 무거운 값 추천
private CharacterController _controller;
private PlayerInputActions _inputActions;
private Vector2 _moveInput;
private Vector3 _velocity; // 수직 속도 (중력용)
private bool _isGrounded;
void Awake()
{
_controller = GetComponent<CharacterController>();
_inputActions = new PlayerInputActions();
// 점프 액션 연결
_inputActions.Player.Jump.performed += ctx => OnJump();
}
void OnEnable() => _inputActions.Enable();
void OnDisable() => _inputActions.Disable();
void Update()
{
// [해결책] 터널 이동 중이라면 일반 이동/중력 로직을 모두 중단합니다.
if (GetComponent<TunnelTraveler>().IsTraveling)
{
return;
}
// 1. 바닥 체크 (CharacterController의 기능 활용)
_isGrounded = _controller.isGrounded;
if (_isGrounded && _velocity.y < 0)
{
// 바닥에 닿아있을 때는 아주 작은 하방 힘만 유지 (안정성)
_velocity.y = -2f;
}
// 2. 이동 로직
_moveInput = _inputActions.Player.Move.ReadValue<Vector2>();
Vector3 move = transform.right * _moveInput.x + transform.forward * _moveInput.y;
_controller.Move(move * moveSpeed * Time.deltaTime);
// 3. 중력 적용
_velocity.y += gravity * Time.deltaTime;
// 4. 최종 수직 이동 적용 (중력/점프 속도)
_controller.Move(_velocity * Time.deltaTime);
}
private void OnJump()
{
// TunnelTraveler가 이동 중인지 체크 (상태 변수 활용)
if (GetComponent<TunnelTraveler>().IsTraveling) return;
if (_isGrounded)
{
_velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
// 터널 이동 등 외부에서 중력을 초기화해야 할 때 사용
public void ResetVelocity()
{
_velocity.y = 0;
}
}