2025-01-02 12:15:45 +08:00

103 lines
3.6 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/*******************************************************************************
*Create By CG
*Function 右键按下旋转物体,左键按下平移摄像机,滚轮缩放摄像机远近
*******************************************************************************/
namespace CG.UTility
{
public class CameraGeoCtrl : MonoBehaviour
{
/// <summary>
/// 需要旋转的物体
/// </summary>
[SerializeField]
private Transform _cenTran;
private float _rotSpeed = 5.12f;// 256.0f;
public float _RotSpeed { get => _rotSpeed/** ZXK.GYJQR.GameManager.Instance._CurMouseFlexible*/;}
private float _moveSpeed = 0.06f;// 3.0f;
public float _MoveSpeed { get => _moveSpeed /** ZXK.GYJQR.GameManager.Instance._CurMouseFlexible*/; }
private float _zoomSpeed = 1.6f;// 80.0f;
public float _ZoomSpeed { get => _zoomSpeed /** ZXK.GYJQR.GameManager.Instance._CurMouseFlexible*/; }
private float _minZoom = 5.0f;
private float _maxZoom = 100f;
private float rotX = 0.0f;
private float rotY = 0.0f;
private float posX = 0.0f;
private float posY = 0.0f;
//是否禁止旋转
[ReadOnly]
public bool _RotForbid = false;
private void OnEnable()
{
Vector3 angles = transform.eulerAngles;
rotX = angles.y;
rotY = angles.x;
Vector3 pos = transform.localPosition;
posX = pos.x;
posY = pos.y;
}
private void Update()
{
if (!EventSystem.current.IsPointerOverGameObject())
{
SetCamDistance();
SetCamPosition();
if (!_RotForbid)
{
SetCamRotation();
}
}
}
/// <summary>
/// 设置摄像机镜头远近
/// </summary>
private void SetCamDistance()
{
//transform.localPosition += transform.forward * Input.mouseScrollDelta.y * Time.deltaTime * _ZoomSpeed;
float zoom = transform.GetComponent<Camera>().fieldOfView;
if (zoom < _minZoom && Input.mouseScrollDelta.y > 0 || zoom > _maxZoom && Input.mouseScrollDelta.y < 0)
{
return;
}
transform.GetComponent<Camera>().fieldOfView -= Input.mouseScrollDelta.y * Time.deltaTime * _ZoomSpeed;
}
private void SetCamPosition()
{
float mouse_x = Input.GetAxis("Mouse X");
float mouse_y = Input.GetAxis("Mouse Y");
if (Input.GetKey(KeyCode.Mouse1))
{
posX = mouse_x * _MoveSpeed * Time.deltaTime;
posY = mouse_y * _MoveSpeed * Time.deltaTime;
//WDebug.Log($"{posX}_{posY}");
transform.Translate(new Vector3(-posX, -posY, 0), Space.Self);
}
}
private void SetCamRotation()
{
float mouse_x = Input.GetAxis("Mouse X");
float mouse_y = Input.GetAxis("Mouse Y");
if (Input.GetKey(KeyCode.Mouse0))
{
//WDebug.Log("速度:" + _RotSpeed);
rotX = mouse_x * _RotSpeed * Time.deltaTime;
rotY = mouse_y * _RotSpeed * Time.deltaTime;
//rotY = Mathf.Clamp(rotY, -90, 90);//防止翻跟头
//Quaternion rotation = Quaternion.Euler(rotY, rotX, 0);//利用欧拉角防止万向锁
//_cenTran.rotation = rotation;
_cenTran.Rotate(new Vector3(0, -rotX, -rotY), Space.World);
}
}
}
}