PlayerController.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. [RequireComponent(typeof(CharacterController))]
  5. public class PlayerController : MonoBehaviour
  6. {
  7. CharacterController cc;
  8. public Transform ftpCamera;
  9. private float mouseX, mouseY;//鼠标的移动值
  10. public float mouseSensitivity = 120f;//鼠标灵敏度
  11. //限制鼠标y轴
  12. public float minMouseY = -70f;
  13. public float maxMouseY = 70f;
  14. private float xRotation;
  15. public float moveSpeed = 20f;
  16. public float jumpSpeed = 50f;
  17. private float hMove, vMove;
  18. private Vector3 dir;
  19. public float gravity = 9.81f;//重力
  20. private Vector3 velocity;
  21. public Transform groundCheck;
  22. public float checkRadius=0.5f;
  23. public LayerMask groundLayer;
  24. private bool isGround;
  25. private bool isLock;
  26. // Start is called before the first frame update
  27. void Start()
  28. {
  29. cc = GetComponent<CharacterController>();
  30. Cursor.lockState = CursorLockMode.Locked;
  31. Cursor.visible = false;
  32. isLock = false;
  33. }
  34. // Update is called once per frame
  35. void Update()
  36. {
  37. if (Input.GetKeyDown(KeyCode.Q))
  38. {
  39. if (isLock)
  40. {
  41. Cursor.lockState = CursorLockMode.Locked;
  42. Cursor.visible = false;
  43. isLock = false;
  44. }
  45. else
  46. {
  47. Cursor.lockState = CursorLockMode.None;
  48. Cursor.visible = true;
  49. isLock = true;
  50. }
  51. }
  52. if (isLock)
  53. {
  54. return;
  55. }
  56. mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
  57. mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
  58. xRotation -= mouseY;
  59. xRotation = Mathf.Clamp(xRotation, minMouseY, maxMouseY);
  60. transform.Rotate(Vector3.up * mouseX);
  61. ftpCamera.localRotation = Quaternion.Euler(xRotation, 0, 0);
  62. isGround = Physics.CheckSphere(groundCheck.position, checkRadius, groundLayer);
  63. if (isGround && velocity.y < 0)
  64. {
  65. velocity.y = -1f;
  66. }
  67. hMove = Input.GetAxis("Horizontal") * moveSpeed;
  68. vMove = Input.GetAxis("Vertical") * moveSpeed;
  69. dir = transform.forward * vMove + transform.right * hMove;
  70. cc.Move(dir * Time.deltaTime);
  71. if (Input.GetButtonDown("Jump") && isGround)
  72. {
  73. velocity.y = jumpSpeed;
  74. }
  75. velocity.y -= gravity * Time.deltaTime;
  76. cc.Move(velocity * Time.deltaTime);
  77. }
  78. }