1. 程式人生 > >正交相機下實現滾輪按鈕拖動,滾動滾輪縮放的功能

正交相機下實現滾輪按鈕拖動,滾動滾輪縮放的功能

pix spa serial ext 分享 內容 onu bject 開始

實現了一個功能,鼠標滾輪鍵按下可以拖動視野內的物體全體(其實是相機自己在移動),滾動滾輪可以縮放內容(其實是改變相機視野大小)

效果如下

技術分享圖片

代碼奉上

 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 的話會出現鼠標滯後或超前的情況,望指教。

正交相機下實現滾輪按鈕拖動,滾動滾輪縮放的功能