using System.Collections; using System.Collections.Generic; using UnityEngine; public class PanoramaCameraOrbit : MonoBehaviour { //float yRotSpeed = 30f; public float mouseSensivity = 120; private Vector3 mousePrevPos; public float camMoveSpeed = 700f; public float camXRot = 0; public float camYRot = 0; public float camZRot = 0; public Vector3 camFreeModePos; float FildOfViewSpeed = 50; //视角拉近速度 void Start() { } void Update() { Vector3 camPos = GetComponent().transform.position; Vector3 camMoveDir = new Vector3(); Vector3 camDesiredRot = Vector3.zero; if (mouseCursorInFrame()) { if (Input.GetMouseButton(1)) { camYRot -= Input.GetAxis("Mouse X") * (Time.deltaTime * mouseSensivity); camYRot = ClampAngle(camYRot, -360, 360); camXRot += Input.GetAxis("Mouse Y") * (Time.deltaTime * mouseSensivity); camXRot = ClampAngle(camXRot, -85, 85); } if (Input.GetAxis("Mouse ScrollWheel") > 0) { if (this.GetComponent().fieldOfView > 50) { camMoveDir = GetComponent().transform.forward; this.GetComponent().fieldOfView -= Time.deltaTime * FildOfViewSpeed;//视角拉近 } } if (Input.GetAxis("Mouse ScrollWheel") < 0) { if (this.GetComponent().fieldOfView < 70) { camMoveDir = -GetComponent().transform.forward; this.GetComponent().fieldOfView += Time.deltaTime * FildOfViewSpeed;//视角拉远 } } } camDesiredRot = new Vector3(camXRot, camYRot, camZRot); camMoveDir.Normalize(); camMoveDir *= (camMoveSpeed * Time.deltaTime); camFreeModePos += camMoveDir; Vector3 finalPosition = Vector3.Lerp(camPos, camFreeModePos, Time.deltaTime + 0.1f); GetComponent().transform.position = finalPosition; GetComponent().transform.rotation = Quaternion.Slerp(GetComponent().transform.rotation, Quaternion.Euler(camDesiredRot), Time.deltaTime + 0.05f); } private bool mouseCursorInFrame() { Vector3 cursorPos = Input.mousePosition; float xMinCoord = Screen.width * GetComponent().rect.xMin; float yMinCoord = Screen.height * GetComponent().rect.yMin; float xMaxCoord = Screen.width * GetComponent().rect.xMax; float yMaxCoord = Screen.height * GetComponent().rect.yMax; if (cursorPos.x > xMinCoord && cursorPos.x < xMaxCoord && cursorPos.y > yMinCoord && cursorPos.y < yMaxCoord) return true; else return false; } private static float ClampAngle(float angle, float min, float max) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); } }