正交相机下实现滚轮按钮拖动,滚动滚轮缩放的功能

实现了一个功能,鼠标滚轮键按下可以拖动视野内的物体全体(其实是相机自己在移动),滚动滚轮可以缩放内容(其实是改变相机视野大小)

效果如下

代码奉上

 1 using UnityEngine;
 2 using UnityEngine.UI;
 3 
 4 /// <summary>
 5 /// 挂载在主相机上
 6 /// </summary>
 7 public class Cont : MonoBehaviour
 8 {
 9     private new Camera camera;
10     private bool isDrag = false;//是否处在拖动状态
11     private Vector3 startMousePosition;//开始拖动的时候鼠标在屏幕上的位置
12     private Vector3 startCameraPosition;//开始拖动的时候相机在世界空间上的位置
13 
14     private Text text;//显示屏幕分辨率的,可忽略
15     private void Start()
16     {
17         text = GameObject.FindWithTag("Text").GetComponent<Text>();
18         camera = GetComponent<Camera>();
19         temp = camera.orthographicSize;
20 
21         text.text = camera.scaledPixelWidth + "  " + camera.scaledPixelHeight;
22         dragScaleX = 1.0f / camera.scaledPixelHeight;//横向缩放值
23         dragScaleY = 1.0f / camera.scaledPixelHeight;//纵向缩放值
24     }
25 
26     void Update()
27     {
28         Drag();//拖动
29         Scale();//滚轮缩放
30     }
31 
32     [SerializeField]
33     private float ScrollScale = 0.1f;
34     private float temp;
35     private float tempAxis;
36     private void Scale()//滚轮缩放
37     {
38         tempAxis = Input.GetAxis("Mouse ScrollWheel");//获取滚轮输入,-1/0/1
39         if (tempAxis == 0) return;
40 
41         temp -= tempAxis * ScrollScale * temp;
42         if (temp < 0)  //控制不让视野为负值,导致内容被中心对称
43         {
44             temp += tempAxis * ScrollScale * temp;
45             return;
46         }
47         camera.orthographicSize = temp;
48     }
49 
50     private void Drag()//拖动
51     {
52         if (Input.GetMouseButtonDown(2))//滚轮按钮
53         {
54             isDrag = true;
55             startMousePosition = Input.mousePosition;//开始拖动前记录鼠标位置
56             startCameraPosition = transform.localPosition;//开始拖动前记录相机位置
57         }
58         if (Input.GetMouseButtonUp(2))
59         {
60             isDrag = false;
61         }
62 
63         MoveScene();
64     }
65     [SerializeField]
66     private float dragScaleX = 0.001f;
67     [SerializeField]
68     private float dragScaleY = 0.001f;
69     private Vector3 worldDir;
70     private void MoveScene()
71     {
72         if (!isDrag) return;
73 
74         worldDir = (startMousePosition - Input.mousePosition) * 2 * camera.orthographicSize;
75         worldDir.x *= dragScaleX;
76         worldDir.y *= dragScaleY;
77         transform.localPosition = startCameraPosition + worldDir;
78     }
79 
80     private void OnGUI()
81     {
82         text.text = camera.pixelWidth + "  " + camera.pixelHeight;
83     }
84 }

使用的时候只要把组件挂载在主相机上就可以了

功能算是完成了,但是有一点很不解,为什么代码中 22行23行用的都是 1/camera.scaledPixelHeight 。如果不是 camera.scaledPixelHeight 而是 camera.scaledPixelWidth 的话会出现鼠标滞后或超前的情况,望指教。

原文地址:https://www.cnblogs.com/Yukisora/p/8747167.html