MouseLook.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using UnityEngine;
  2. public class MouseLook : MonoBehaviour
  3. {
  4. public float sensitivity = 100f; // 敏感度
  5. public float clampAngle = 80f; // 视角限制角度
  6. private float yMinLimit = -80f; // 最小视角限制
  7. private float yMaxLimit = 80f; // 最大视角限制
  8. private float x = 0f; // 用于存储camera的X角度
  9. private float y = 0f; // 用于存储camera的Y角度
  10. public float zoomSpeed = 5.0f; // 调整速度
  11. public float minFOV = 10.0f; // 最小视角
  12. public float maxFOV = 90.0f; // 最大视角
  13. private Camera cam;
  14. private float currentFOV;
  15. void Start()
  16. {
  17. // 初始化角度
  18. y = transform.eulerAngles.y;
  19. cam = GetComponent<Camera>();
  20. currentFOV = cam.fieldOfView;
  21. }
  22. private float rotateSpeed = 30f;
  23. private float movespeed = 5;
  24. void FixedUpdate()
  25. {
  26. }
  27. bool isenter = false;
  28. public void enter()
  29. {
  30. isenter=true;
  31. }
  32. public void exit()
  33. {
  34. isenter=false;
  35. }
  36. public Transform playerBody; // 角色的body,用于确定转向的参照点
  37. private float xRotation = 0f; // 记录水平旋转角度
  38. Vector3 downv3=Vector3.zero;
  39. void Update()
  40. {
  41. if(!isenter)
  42. return;
  43. // 检查鼠标滚轮是否有移动
  44. float scrollInput = Input.GetAxis("Mouse ScrollWheel");
  45. if (scrollInput != 0)
  46. {
  47. // 根据滚轮输入调整视角
  48. currentFOV -= scrollInput * zoomSpeed;
  49. currentFOV = Mathf.Clamp(currentFOV, minFOV, maxFOV);
  50. cam.fieldOfView = currentFOV;
  51. }
  52. if (Input.GetKey(KeyCode.W))
  53. {
  54. transform.Translate(Vector3.forward * Time.deltaTime * speed*10);
  55. }
  56. else if (Input.GetKey(KeyCode.S))
  57. {
  58. transform.Translate(Vector3.back * Time.deltaTime * speed*10);
  59. }
  60. if (Input.GetKey(KeyCode.A))
  61. {
  62. transform.Translate(Vector3.left * Time.deltaTime * speed*10);
  63. }
  64. else if (Input.GetKey(KeyCode.D))
  65. {
  66. transform.Translate(Vector3.right * Time.deltaTime * speed*10);
  67. }
  68. if (!Input.GetMouseButton(1)&&!Input.GetMouseButton(0)) return;
  69. if (Input.GetMouseButton(0) || Input.GetMouseButton(1))
  70. {
  71. transform.Rotate(Vector3.up, Input.GetAxis("Mouse X") * speed * 10);
  72. transform.Rotate(Vector3.left, Input.GetAxis("Mouse Y") * speed * 10);
  73. transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);
  74. }
  75. if (Input.GetKey(KeyCode.Escape))
  76. {
  77. transform.position = positionReset;
  78. transform.eulerAngles = eulerAnglesReset;
  79. }
  80. }
  81. [Range(0.1f, 10f)]
  82. public float speed = 0.4f;
  83. Vector3 positionReset, eulerAnglesReset;
  84. void Awake()
  85. {
  86. positionReset = transform.position;
  87. eulerAnglesReset = transform.eulerAngles;
  88. }
  89. }