123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using UnityEngine;
-
- public class MouseLook : MonoBehaviour
- {
- public float sensitivity = 100f; // 敏感度
- public float clampAngle = 80f; // 视角限制角度
-
- private float yMinLimit = -80f; // 最小视角限制
- private float yMaxLimit = 80f; // 最大视角限制
-
- private float x = 0f; // 用于存储camera的X角度
- private float y = 0f; // 用于存储camera的Y角度
-
- public float zoomSpeed = 5.0f; // 调整速度
- public float minFOV = 10.0f; // 最小视角
- public float maxFOV = 90.0f; // 最大视角
-
- private Camera cam;
- private float currentFOV;
- void Start()
- {
- // 初始化角度
- y = transform.eulerAngles.y;
- cam = GetComponent<Camera>();
- currentFOV = cam.fieldOfView;
- }
- private float rotateSpeed = 30f;
- private float movespeed = 5;
- void FixedUpdate()
- {
- //第一种控制移动
- float h = Input.GetAxis("Horizontal");
- float v = Input.GetAxis("Vertical");
- //朝一个方向移动 new Vector3(0, 0, v) * speed * Time.deltaTime是个向量
- transform.Translate(new Vector3(0, 0, v) * movespeed * Time.deltaTime); //前后移动
- transform.Rotate(new Vector3(0, h, 0) * rotateSpeed * Time.deltaTime); //左右旋转
- //第二种方式控制移动
- if (Input.GetKey(KeyCode.W)) //前进
- {
- transform.Translate(Vector3.forward * movespeed * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.S)) //后退
- {
- transform.Translate(Vector3.back * movespeed * Time.deltaTime);
- }
- if (Input.GetKey(KeyCode.A))//向左旋转
- {
- transform.Rotate(0,-rotateSpeed * Time.deltaTime,0);
- }
- if (Input.GetKey(KeyCode.D))//向右旋转
- {
- transform.Rotate(0, rotateSpeed * Time.deltaTime, 0);
- }
- }
- void Update()
- { // 检查鼠标滚轮是否有移动
- float scrollInput = Input.GetAxis("Mouse ScrollWheel");
- if (scrollInput != 0)
- {
- // 根据滚轮输入调整视角
- currentFOV -= scrollInput * zoomSpeed;
- currentFOV = Mathf.Clamp(currentFOV, minFOV, maxFOV);
- cam.fieldOfView = currentFOV;
- }
- // 若鼠标右键未按下,则直接返回
- if (!Input.GetMouseButton(1)&&!Input.GetMouseButton(0)) return;
-
- // 获取鼠标移动的X和Y方向的值
- float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
- float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
-
- // 更新视角
- x -= mouseY;
- x = Mathf.Clamp(x, yMinLimit, yMaxLimit);
- y += mouseX;
-
- // 应用新的视角
- transform.eulerAngles = new Vector3(x, y, 0f);
- }
- }
|