2025-10-15 21:31:13 +08:00
|
|
|
|
using System;
|
|
|
|
|
using Core;
|
2025-10-17 15:10:19 +08:00
|
|
|
|
using Script.Gameplay.Input;
|
2025-10-15 21:31:13 +08:00
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
2025-10-20 10:12:07 +08:00
|
|
|
|
namespace Script.Gameplay.Player
|
2025-10-15 21:31:13 +08:00
|
|
|
|
{
|
|
|
|
|
public class PlayerMoveController : MonoBehaviour
|
|
|
|
|
{
|
|
|
|
|
[Header("Movement Settings")]
|
|
|
|
|
[Tooltip("移动速度(米/秒)")]
|
|
|
|
|
public float speed = 5f;
|
|
|
|
|
[Tooltip("跳跃高度(米)")]
|
|
|
|
|
public float jumpHeight = 2f;
|
|
|
|
|
[Tooltip("重力加速度(米/秒²)")]
|
|
|
|
|
public float gravity = -9.81f;
|
|
|
|
|
|
|
|
|
|
[Header("Ground Check")]
|
|
|
|
|
[Tooltip("检测地面的位置(通常为角色脚下)")]
|
|
|
|
|
public Transform groundCheck;
|
|
|
|
|
[Tooltip("地面检测半径")]
|
|
|
|
|
public float groundDistance = 0.4f;
|
|
|
|
|
[Tooltip("地面层(LayerMask)")]
|
|
|
|
|
public LayerMask groundMask;
|
|
|
|
|
|
|
|
|
|
private float initSpeed;
|
|
|
|
|
|
|
|
|
|
private CharacterController characterController;
|
|
|
|
|
private Vector3 velocity;
|
|
|
|
|
private bool isGrounded;
|
|
|
|
|
private IInputManager inputManager;
|
|
|
|
|
|
|
|
|
|
private void Awake()
|
|
|
|
|
{
|
|
|
|
|
characterController = GetComponent<CharacterController>();
|
|
|
|
|
if (characterController == null)
|
|
|
|
|
Debug.LogError("PlayerMoveController 需要 CharacterController 组件!");
|
|
|
|
|
|
|
|
|
|
initSpeed = speed;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Start()
|
|
|
|
|
{
|
|
|
|
|
inputManager = InputManager.Instance;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void Update()
|
|
|
|
|
{
|
|
|
|
|
// 地面检测
|
|
|
|
|
if (groundCheck != null)
|
|
|
|
|
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
|
|
|
|
|
else
|
|
|
|
|
isGrounded = characterController.isGrounded;
|
|
|
|
|
|
|
|
|
|
if (isGrounded && velocity.y < 0)
|
|
|
|
|
velocity.y = -2f; // 保持贴地
|
|
|
|
|
|
|
|
|
|
Vector2 inputMove = inputManager.Move;
|
|
|
|
|
// 获取输入
|
|
|
|
|
float x = inputMove.x;
|
|
|
|
|
float z = inputMove.y;
|
|
|
|
|
|
|
|
|
|
// 按玩家朝向移动
|
|
|
|
|
Vector3 move = transform.right * x + transform.forward * z;
|
|
|
|
|
characterController.Move(move * speed * Time.deltaTime);
|
|
|
|
|
|
|
|
|
|
// 跳跃
|
|
|
|
|
if (isGrounded && inputManager.JumpPressed)
|
|
|
|
|
{
|
|
|
|
|
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 重力
|
|
|
|
|
velocity.y += gravity * Time.deltaTime;
|
|
|
|
|
characterController.Move(velocity * Time.deltaTime);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void SetSpeed(float newSpeed)
|
|
|
|
|
{
|
|
|
|
|
speed = newSpeed;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void ResetSpeed()
|
|
|
|
|
{
|
|
|
|
|
speed = initSpeed;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|