MouseLook.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.   float h = Input.GetAxis("Horizontal");
  28.   float v = Input.GetAxis("Vertical");
  29.   //朝一个方向移动 new Vector3(0, 0, v) * speed * Time.deltaTime是个向量
  30.   transform.Translate(new Vector3(0, 0, v) * movespeed * Time.deltaTime);  //前后移动
  31.   transform.Rotate(new Vector3(0, h, 0) * rotateSpeed * Time.deltaTime); //左右旋转
  32.   //第二种方式控制移动
  33.   if (Input.GetKey(KeyCode.W)) //前进
  34.   {
  35.     transform.Translate(Vector3.forward * movespeed * Time.deltaTime);
  36.   }
  37.   if (Input.GetKey(KeyCode.S)) //后退
  38.   {
  39.     transform.Translate(Vector3.back * movespeed * Time.deltaTime);
  40.   }
  41.   if (Input.GetKey(KeyCode.A))//向左旋转
  42.   {
  43.     transform.Rotate(0,-rotateSpeed * Time.deltaTime,0);
  44.   }
  45.   if (Input.GetKey(KeyCode.D))//向右旋转
  46.   {
  47.     transform.Rotate(0, rotateSpeed * Time.deltaTime, 0);
  48.   }
  49. }
  50. void Update()
  51. { // 检查鼠标滚轮是否有移动
  52. float scrollInput = Input.GetAxis("Mouse ScrollWheel");
  53. if (scrollInput != 0)
  54. {
  55. // 根据滚轮输入调整视角
  56. currentFOV -= scrollInput * zoomSpeed;
  57. currentFOV = Mathf.Clamp(currentFOV, minFOV, maxFOV);
  58. cam.fieldOfView = currentFOV;
  59. }
  60. // 若鼠标右键未按下,则直接返回
  61. if (!Input.GetMouseButton(1)&&!Input.GetMouseButton(0)) return;
  62. // 获取鼠标移动的X和Y方向的值
  63. float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
  64. float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
  65. // 更新视角
  66. x -= mouseY;
  67. x = Mathf.Clamp(x, yMinLimit, yMaxLimit);
  68. y += mouseX;
  69. // 应用新的视角
  70. transform.eulerAngles = new Vector3(x, y, 0f);
  71. }
  72. }