using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; /******************************************************************************** *Create By CG *Function 摄像机环绕某个物体旋转展示 *鼠标滚轮:镜头远近-按住鼠标右键,拖动鼠标:摄像机绕某个物体上下左右旋转 *********************************************************************************/ namespace ZXK.UTility { public class CameraAroundCtrl : MonoBehaviour { /// /// 需要围绕的物体 /// public Transform _CenObj; public float _RotSpeed = 256; public float _ZoomSpeed = 30; private float x = 0.0f; private float y = 0.0f; private float distance = 0.0f; public bool IsCameraMove = false; private void OnEnable() { Vector3 angles = transform.eulerAngles; x = angles.y; y = angles.x; distance = (transform.position - _CenObj.position).magnitude; } private void Update() { } private void LateUpdate() { if (!EventSystem.current.IsPointerOverGameObject()) { SetCamDistance(); SetCamRotation(); IsCameraMove = true; } else { IsCameraMove = false; } } /// /// 设置摄像机距离物体远近 /// private void SetCamDistance() { transform.localPosition += transform.forward * Input.mouseScrollDelta.y * Time.deltaTime * _ZoomSpeed; distance = (transform.position - _CenObj.position).magnitude; } /// /// 设置摄像机围绕物体旋转 /// private void SetCamRotation() { float mouse_x = Input.GetAxis("Mouse X"); float mouse_y = Input.GetAxis("Mouse Y"); if (Input.GetKey(KeyCode.Mouse1)) { x += mouse_x * _RotSpeed * Time.deltaTime; y -= mouse_y * _RotSpeed * Time.deltaTime; y = Mathf.Clamp(y, -90, 90);//防止翻跟头 Quaternion rotation = Quaternion.Euler(y, x, 0);//利用欧拉角防止万向锁 Vector3 position = rotation *new Vector3(0,0,-distance) + _CenObj.position;//求得旋转后位置 transform.rotation = rotation; transform.position = position; } } } }