Files
HuoChaiRen/Scripts/MoveForPlayerCamera.cs
2026-09-24 16:54:34 +08:00

382 lines
17 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class moveForPlayer : MonoBehaviour
{
[Header("相机设置")]
[SerializeField] private GameObject playerCamera; // 玩家相机,用于计算投
[Header("跳跃缓存触发阈值")]
[SerializeField] private float willJumpFloat = 0.3f;
[Header("移动设置")]
[SerializeField] private float moveSpeed = 5f; // 基础移动速度
[SerializeField] private float sprintMultiplier = 2f; // 加速倍数(按住Shift)
[SerializeField] private float rotationSpeed = 2f; // 鼠标旋转灵敏度
/* [Header("平滑设置")]
[SerializeField] private float smoothTime = 0.05f; // 移动平滑时间 */
[Header("可切换摄像头")]
[SerializeField] private Camera[] cameras; // 可切换的摄像机数组
[Header("跳跃设置")]
[SerializeField] private float jumpHeight = 2f; // 跳跃高度
[SerializeField] private float gravity = 9.81f; // 重力加速度
[SerializeField] private float fallMultiplier = 2.5f; // 下落加速倍率(让下落更自然)
[SerializeField] private float heartHeight = 3f; // 掉落高度(超过这个高度就会掉血)
[Header("后座力系统")]
[SerializeField] private float recoilOffsetX = 0f; // 累积的后座力垂直偏移
[SerializeField] private float recoilOffsetY = 0f; // 累积的后座力水平偏移
[SerializeField] private float recoilRecoveryXSpeed = 5f; // 后座力恢复
[SerializeField] private float recoilRecoveryYSpeed = 8f; // 恢复
[SerializeField] private float recoilRecoveryX = 5f; // 后座力恢复
[SerializeField] public float recoilRecoveryY = 8f; // 恢复速度
[Header("其他设置")]
[SerializeField] private Animator playerAnimator; // 玩家动画控制器
private float currentRotationX = 0f; // 存储当前X轴旋转(俯仰角),范围-89~89度
private float currentRotationY = 0f; // 存储当前Y轴旋转(偏航角),可以无限累加
//private Vector3 velocityRef = Vector3.zero; // SmoothDamp的内部速度缓存,用于计算平滑
private bool isInputEnabled = false; // 是否允许输入,初始为false,按下ESC键后切换为true
private bool isMouseLocked = false; // 鼠标是否锁定,初始为false,按下ESC键后切换为true
private CharacterController controller; // 玩家控制器组件引用
private Vector3 translationY; // 用于存储Y轴方向的移动量,避免直接修改transform.position
private bool isJumping = false; // 玩家是否正在跳跃
private bool isFalling = false; // 玩家是否正在下落
private Vector3 GroundPosition; // 玩家在地面上的位置,用于判断是否离开地面
private float timer; // 用于计时,判断玩家是否离开地面超过一定时间
private bool isGrounded; // 玩家是否在地面上
private bool willJump = false; // 玩家是否即将跳跃
private float offsetY = 0f; // 用于存储摄像机的Y轴偏移量,避免直接修改transform.position
private float offsetX = 0f; // 用于存储摄像机的X轴偏移量,避免直接修改transform.position
private bool isRecoilRecovering = false; // 是否正在恢复后座力
private float timerForStart = 0f; // 用于计时,判断是否开始
void Start()
{
for (int i = 0; i < cameras.Length; i++)
{
if (i == 0)
{
EnableInput(); // 启用输入
LockMouse(); // 锁定鼠标
cameras[i].enabled = true; // 启用第一个摄像机
}
else
{
cameras[i].enabled = false; // 禁用其他摄像机
}
}
controller = GetComponent<CharacterController>();
Vector3 euler = transform.eulerAngles;// 获取初始旋转角度
currentRotationX = euler.x;
currentRotationY = euler.y;
controller.Move(Vector3.down * 100f * Time.deltaTime);// 确保玩家在地面上,避免一开始就悬空
GroundPosition = transform.position; // 初始化地面位置
isGrounded = controller.isGrounded; // 初始化玩家是否在地面上
}
// Update is called once per frame
void Update()
{
/* timerForStart += Time.deltaTime;
if(timerForStart < 20f)
{
return; // 等待0.5秒后再执行后续逻辑
} */
HandleRecoilTimeDecay();
if (Input.GetKeyDown(KeyCode.T))
{
// 切换摄像机
for (int i = 0; i < cameras.Length; i++)
{
if (cameras[i].enabled)
{
cameras[i].enabled = false;
cameras[(i + 1) % cameras.Length].enabled = true;
if (i == 0)
{
LockMouse(); // 切换到第一个摄像机时锁定鼠标
EnableInput(); // 启用输入
}
else
{
DisableInput(); // 禁用输入
FreeMouse(); // 释放鼠标
}
break;
}
}
}
if (isInputEnabled)
{
HandleAltKey();
HandleMovement();
if (isMouseLocked)
{
HandleRotation();
}
else
{
//HandleForRecoilTimeDecay();
}
//ApplySmoothMovement();
}
}
void HandleRotation()
{
float mouseX = Input.GetAxis("Mouse X") * rotationSpeed; // 鼠标X轴移动量,乘以旋转速度
float mouseY = Input.GetAxis("Mouse Y") * rotationSpeed; // 鼠标Y轴移动量,乘以旋转速度
currentRotationY += mouseX + offsetX;
currentRotationX -= mouseY + offsetY;
currentRotationX = Mathf.Clamp(currentRotationX, -89f, 89f);
//playerCamera.transform.rotation = Quaternion.Euler(currentRotationX, currentRotationY, 0f);
transform.rotation = Quaternion.Euler(0f, currentRotationY, 0f);
Quaternion rotation = Quaternion.Euler(currentRotationX, currentRotationY, 0);
// 核心公式:玩家位置 - (相机朝向 * 距离) + 高度偏移
Vector3 targetPosition = transform.position - (rotation * Vector3.forward * 2f); // 10f是相机距离,2f是高度偏移
// 3. 将相机的“位置”平滑移动到目标位置
//playerCamera.transform.position = Vector3.Lerp(playerCamera.transform.position, targetPosition, 10f * Time.deltaTime);
playerCamera.transform.position = targetPosition; // 直接设置位置,避免平滑移动导致的穿模问题
// 4. 让相机始终“看向”玩家上半身的位置
playerCamera.transform.LookAt(transform.position+ Vector3.up * 0.5f); // 让相机看向玩家上半身的位置,避免看向地面
targetPosition = transform.position - (rotation * Vector3.forward * 4f)+Vector3.up;// + rotation * Vector3.right * 1f; // 10f是相机距离,2f是高度偏移
playerCamera.transform.position = targetPosition;
}
void HandleForRecoilTimeDecay()
{
currentRotationY += offsetX;
currentRotationX -= offsetY;
currentRotationX = Mathf.Clamp(currentRotationX, -89f, 89f);
playerCamera.transform.rotation = Quaternion.Euler(currentRotationX, currentRotationY, 0f);
transform.rotation = Quaternion.Euler(0f, currentRotationY, 0f);
}
void HandleRecoilTimeDecay()
{
if (recoilOffsetX != 0 || recoilOffsetY > 0)
{
if (recoilOffsetX != 0)
{
offsetX = recoilOffsetX * recoilRecoveryXSpeed * Time.deltaTime; // 将累积的后座力偏移应用到摄像机的X轴旋转上
recoilOffsetX -= offsetX; // 后座力恢复
if (-0.1f < recoilOffsetX && recoilOffsetX < 0.1f)
{
recoilOffsetX = 0f;
}
}
if (recoilOffsetY > 0)
{
offsetY = recoilOffsetY * recoilRecoveryYSpeed * Time.deltaTime; // 将累积的后座力偏移应用到摄像机的Y轴旋转上
recoilOffsetY -= offsetY; // 后座力恢复
if (recoilOffsetY < 0.1f)
{
recoilOffsetY = 0f;
}
}
}
else if (isRecoilRecovering)
{
recoilOffsetX = Mathf.MoveTowards(recoilOffsetX, 0f, recoilRecoveryX * Time.deltaTime); // 后座力恢复
recoilOffsetY = Mathf.MoveTowards(recoilOffsetY, 0f, recoilRecoveryY * Time.deltaTime); // 后座力恢复
if (recoilOffsetX < 0.01f)
{
recoilOffsetX = 0f;
isRecoilRecovering = false; // 停止恢复后座力
}
if (recoilOffsetY < 0.01f)
{
recoilOffsetY = 0f;
isRecoilRecovering = false; // 停止恢复后座力
}
}
else
{
offsetX = 0f; // 将累积的后座力偏移应用到摄像机的X轴旋转上
offsetY = 0f; // 将累积的后座力偏移应用到摄像机的Y轴旋转上
}
}
void HandleMovement()
{
if (controller.isGrounded && isJumping)
{
isFalling = false; // 玩家在空中且Y轴方向的移动量小于0,设置下落状态为true
}
else if (controller.isGrounded)
{
if (transform.position.y - GroundPosition.y < -heartHeight)
{
// 玩家从高处掉落,需要掉血
Debug.Log("玩家从高处掉落,需要掉血");
//GameManager.Instance.BeShoted(10); // 调用GameManager的BeShoted方法,传入掉血值
GroundPosition = transform.position; // 更新地面位置
isFalling = false; // 玩家在空中且Y轴方向的移动量
isJumping = false; // 玩家在空中且Y轴方向的移动量
timer = 0f; // 重置计时器
}
else
{
GroundPosition = transform.position; // 更新地面位置
isFalling = false; // 玩家在空中且Y轴方向的移动量
isJumping = false; // 玩家在空中且Y轴方向的移动量
timer = 0f; // 重置计时器
}
}
else if (isGrounded && !controller.isGrounded && !isFalling && !isJumping)
{
isFalling = true; // 玩家在空中且Y轴方向的移动量小于0,设置下落状态为true
timer = 0f; // 重置计时器
}
if (transform.position.y >= (GroundPosition.y + jumpHeight) && !isFalling)
{
timer = 0f; // 玩家在空中且Y轴方向的移动量大于0,重置计时器为0
transform.position = new Vector3(transform.position.x, GroundPosition.y + jumpHeight, transform.position.z); // 玩家在空中且Y轴方向的移动量大于0,重置Y轴方向的移动量为1.5
isFalling = true; // 玩家在空中且Y轴方向的移动量大于0,设置下落状态为true
isJumping = false; // 玩家在空中且Y轴方向的移动量大于0,设置跳跃状态为false
}
isGrounded = controller.isGrounded; // 检测玩家是否在地面上
if (isJumping)
{
// 计算跳跃速度,使用公式 v = sqrt(2 * g * h)
float jumpVelocity = (Mathf.Sqrt(2f * jumpHeight / gravity) - timer) * gravity; // 计算跳跃速度,使用公式 v = sqrt(2 * g * h)
timer += Time.deltaTime; // 增加计时器
translationY.y = jumpVelocity * Time.deltaTime; // 设置Y轴方向的移动量为跳跃速度
}
else if (isFalling)
{
// 计算跳跃速度,使用公式 v = sqrt(2 * g * h)
float jumpVelocity = gravity * timer; // 计算跳跃速度,使用公式 v = g * t
timer += Time.deltaTime; // 增加计时器
translationY.y = -jumpVelocity * Time.deltaTime; // 设置Y轴方向的移动量为跳跃速度
}
else
{
translationY.y = 0f; // 在地面上,Y轴方向的移动量为0
}
float horizontal = Input.GetAxis("Horizontal"); // 获取水平输入(A/D或左右箭头)
float vertical = Input.GetAxis("Vertical"); // 获取垂直输入(W/S或上下箭头)
if (!willJump && Mathf.Approximately(horizontal, 0f) && !Input.GetKeyDown(KeyCode.Space) && Mathf.Approximately(vertical, 0f))
{
if (translationY.y != 0f)
{
controller.Move(translationY); // 没有输入,只处理Y轴方向的移动
}
else
{
controller.Move(Vector3.down * 10f * Time.deltaTime);
}
//playerAnimator.SetBool("isRunning", false); // 设置动画参数
return; // 没有输入,直接返回
}
if (controller.isGrounded && Input.GetKeyDown(KeyCode.Space))
{
timer = 0f; // 玩家按下跳跃键,重置计时器为0
isJumping = true; // 玩家按下跳跃键,设置跳跃状态为true
isFalling = false; // 玩家按下跳跃键,设置下落状态为false
willJump = false; // 玩家按下跳跃键,设置即将跳跃状态为false
}
else if (willJump && controller.isGrounded)
{
timer = 0f; // 玩家按下跳跃键,重置计时器为0
isJumping = true; // 玩家按下跳跃键,设置跳跃状态为true
isFalling = false; // 玩家按下跳跃键,设置下落状态为false
willJump = false; // 玩家按下跳跃键,设置即将跳跃状态为false
}
else if (Input.GetKeyDown(KeyCode.Space) && isFalling && transform.position.y <= GroundPosition.y + willJumpFloat)
{
willJump = true; // 玩家按下跳跃键,设置即将跳跃状态为true
}
float currentSpeed = moveSpeed;
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
{
currentSpeed *= sprintMultiplier; // 按住Shift键,加速移动
}
Vector3 forward = playerCamera.transform.forward; // 获取摄像机的前方向
Vector3 right = playerCamera.transform.right; // 获取摄像机的右方向
forward.y = 0f;
right.y = 0f;
// 重新归一化,保持方向向量长度为1
forward.Normalize();
right.Normalize();
Vector3 moveDirection = (forward * vertical + right * horizontal).normalized; // 计算移动方向并归一化
if (moveDirection.magnitude > 1f)
{
moveDirection.Normalize(); // 防止斜向移动速度过快
}
if (translationY.y == 0f)
{
//playerAnimator.SetBool("isRunning", moveDirection.magnitude > 0f); // 设置动画参数
controller.Move(moveDirection * currentSpeed * Time.deltaTime + Vector3.down * 10f * Time.deltaTime); // 使用CharacterController移动
}
else
{
controller.Move(moveDirection * currentSpeed * Time.deltaTime + translationY); // 使用CharacterController移动
}
}
void ApplySmoothMovement()
{
// 使用 SmoothDamp 实现平滑跟随,避免移动突兀
// 参数:当前位置,目标位置,引用速度变量,平滑时间
/* playerRigidbody.position = Vector3.SmoothDamp(
transform.position,
targetPosition,
ref velocityRef,
smoothTime
); */
//playerRigidbody.MovePosition(targetPosition);
}
void HandleAltKey()// 检测Alt键状态,切换鼠标锁定状态
{
if (!Input.GetKey(KeyCode.LeftAlt) && !Input.GetKey(KeyCode.RightAlt))
{
LockMouse();
}
else
{
FreeMouse();
}
}
void FreeMouse()// 释放鼠标
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
isMouseLocked = false;
}
void LockMouse()// 锁定鼠标
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
isMouseLocked = true;
}
public void EnableInput()// 启用输入
{
isInputEnabled = true;
}
public void DisableInput()// 禁用输入
{
isInputEnabled = false;
}
public void ApplyRecoil(float recoilAmountX, float recoilAmountY)
{
// 累积后座力偏移,限制在最大值范围内
recoilOffsetX += recoilAmountX;
recoilOffsetY += recoilAmountY;
}
public void ChangeIsRecoilRecovering(bool isRecovering)
{
recoilOffsetX = -recoilRecoveryX;
recoilOffsetY = -recoilRecoveryY;
isRecoilRecovering = isRecovering;
}
}