public float speed = 5f; // 移动速度
public float sprintMultiplier = 1.5f; // 冲刺速度倍率
public float jumpForce = 8f; // 初始跳跃力度
public float jumpCooldown = 2f; // 跳跃冷却时间
private CharacterController characterController;
private bool canJump = true;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
Move();
MouseLook();
// 检测鼠标左键按下
if (Input.GetMouseButtonDown(0))
{
ToggleCursorVisibility(false); // 隐藏鼠标
}
}
void Move()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
// 按下 Shift 键时增加速度
float currentSpeed = Input.GetKey(KeyCode.LeftShift) ? speed * sprintMultiplier : speed;
Vector3 moveDirection = transform.right * x + transform.forward * z;
moveDirection.Normalize();
moveDirection *= currentSpeed * Time.deltaTime;
// 处理跳跃
if (Input.GetButtonDown("Jump") && characterController.isGrounded && canJump)
{
StartCoroutine(JumpCoroutine());
}
// 重力
moveDirection.y -= 9.8f * Time.deltaTime;
characterController.Move(moveDirection);
}
IEnumerator JumpCoroutine()
{
float airTime = 0f;
float jumpDuration = 0.1f; // 跳跃的持续时间
while (airTime < jumpDuration)
{
float jumpHeight = Mathf.Lerp(0f, jumpForce, airTime / jumpDuration);
Vector3 jumpVelocity = Vector3.up * jumpHeight;
characterController.Move(jumpVelocity * Time.deltaTime);
airTime += Time.deltaTime;
yield return null;
}
canJump = false; // 触发跳跃后设置为false
Invoke("ResetJump", jumpCooldown); // 延迟 jumpCooldown 秒后重置 canJump 为 true
}
void MouseLook()
{
float mx = Input.GetAxis("Mouse X");
float my = -Input.GetAxis("Mouse Y");
Quaternion qx = Quaternion.Euler(0, mx, 0);
Quaternion qy = Quaternion.Euler(my, 0, 0);
transform.rotation = qx * transform.rotation;
transform.rotation = transform.rotation * qy;
float angle = transform.eulerAngles.x;
if (angle > 180) { angle -= 360; }
if (angle < -180) { angle += 360; }
if (angle > 80)
{
Debug.Log("A" + transform.eulerAngles.x);
transform.eulerAngles = new Vector3(80, transform.eulerAngles.y, 0);
}
if (angle < -80)
{
Debug.Log("A" + transform.eulerAngles.x);
transform.eulerAngles = new Vector3(-80, transform.eulerAngles.y, 0);
}
}
void ToggleCursorVisibility(bool visible)
{
Cursor.lockState = visible ? CursorLockMode.None : CursorLockMode.Locked;
Cursor.visible = visible;
}
void ResetJump()
{
canJump = true;
}
}