using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;

public class PlayerMovement : MonoBehaviour
{
// 是否接地
private bool isGrounded = false;
// 距离地面
public float groundDistance = 1f;
// 玩家速度
public float playerSpeed = 5f;
// 敏感度
public float sensitivity = 5f;
// 旋转角度
private float rotationAngle = 0f;
// 相机
public Transform playerCamera;
// rigidbody
private Rigidbody rb;

void Start()
{
    // 锁定鼠标
    Cursor.lockState = CursorLockMode.Locked;
    // 获取rigidbody
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    // 检测是否接地
    if (Physics.Raycast(transform.position, Vector3.down, groundDistance + 0.1f))
    {
        isGrounded = true;
    }
    else
    {
        isGrounded = false;
    }

    // 获取水平和垂直输入
    float horizontal = Input.GetAxis("Horizontal") * playerSpeed / 2f;
    float vertical = Input.GetAxis("Vertical") * playerSpeed;

    // 计算移动方向
    Vector3 move = (transform.forward * vertical) + (transform.right * horizontal);

    // 设置rigidbody的线性速度
    rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
}

void Update()
{
    // 获取鼠标输入
    float mouseX = Input.GetAxis("Mouse X") * sensitivity;
    float mouseY = Input.GetAxis("Mouse Y") * sensitivity;

    // 旋转角度
    rotationAngle -= mouseY;
    rotationAngle = Mathf.Clamp(rotationAngle, -90f, 90f);

    // 设置相机的局部旋转
    playerCamera.localRotation = Quaternion.Euler(rotationAngle, 0f, 0f);

    // 旋转玩家
    transform.Rotate(Vector3.up * mouseX);

    // 跳跃
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        // 设置rigidbody的线性速度
        rb.velocity = new Vector3(rb.velocity.x, 10f, rb.velocity.z);
    }
}

}