脚本挂在相机上
using System;
using UnityEngine;
public class RotateScrollControl : MonoBehaviour
{
[SerializeField]
[Tooltip("环绕中心")]
private Transform _centerTransform;
[SerializeField]
[Tooltip("环绕速率")]
private float _aroundRate;
[SerializeField]
[Tooltip("旋转速率")]
private float _rotateRate;
[SerializeField]
[Tooltip("向上旋转最大角度")]
private float _maxUpAngle;
[SerializeField]
[Tooltip("向下旋转最大角度")]
private float _maxDownAngle;
[SerializeField]
[Tooltip("滚动速率")]
private float _scrollRate;
private Vector3 _leftPrePosition;
private Vector3 _rightPrePosition;
/// <summary>
/// 鼠标左键旋转相机
/// </summary>
private void RotateSelf()
{
if (Input.GetMouseButtonDown(0))
{
_leftPrePosition = Input.mousePosition;
Debug.Log("Input.mousePosition = " + Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
var delta = Input.mousePosition - _leftPrePosition;
_leftPrePosition = Input.mousePosition;
Debug.Log($"delta = ({delta.x}, {delta.y}, {delta.z})");
float eulerAnglesX = transform.localEulerAngles.x - delta.y * _rotateRate;
eulerAnglesX = Mathf.Clamp(eulerAnglesX, _maxUpAngle, _maxDownAngle);
float eulerAnglesY = transform.localEulerAngles.y + delta.x * _rotateRate;
transform.localEulerAngles = new Vector3(eulerAnglesX, eulerAnglesY,0);
Debug.Log($"transform.localEulerAngles = {transform.localEulerAngles}");
}
}
/// <summary>
/// 鼠标右键绕物体左右旋转
/// </summary>
private void RotateAround()
{
if (Input.GetMouseButtonDown(1))
{
_rightPrePosition = Input.mousePosition;
}
if(Input.GetMouseButton(1))
{
var delta = Input.mousePosition - _rightPrePosition;
_rightPrePosition = Input.mousePosition;
Debug.Log($"delta = {delta}");
transform.RotateAround(_centerTransform.position,Vector3.up, delta.x * _aroundRate);
}
}
/// <summary>
/// 滑动鼠标滚轮缩放相机
/// </summary>
private void MouseScrollWheel()
{
if (Math.Abs(Input.GetAxis("Mouse ScrollWheel")) > 0.001f)
{
gameObject.transform.Translate(new Vector3(0, 0, Input.GetAxis("Mouse ScrollWheel") * _scrollRate));
}
}
void Update()
{
RotateSelf();
RotateAround();
MouseScrollWheel();
}
}