前提将脚本挂载到Camera上
拖拽的原理 :点击左键记录坐标P1,滑动记录当前坐标P2
计算P1、P2的坐标差dx、dy, 根据dx和dy正负确定移动方向
缩放原理:根据滚轮控制摄像机视野和摄像机的正交投影
旋转原理:鼠标右键不太好控制,于是指定了键盘
就是直接给旋转赋值
完整代码如下:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseMoveandScale : MonoBehaviour { Vector2 p1, p2,p3,p4;//用来记录鼠标的位置,以便计算移动距离 void Start () { } void Update () { translationDrag(); zoom(); rotate(); } private void translationDrag() { //通过鼠标X坐标拖动场景 if (Input.GetMouseButtonDown(0)) { //鼠标左键按下时记录鼠标位置p1 p1 = new Vector2(Input.mousePosition.x, Input.mousePosition.y); } if (Input.GetMouseButton(0)) { //鼠标左键拖动时记录鼠标位置p2 p2 = new Vector2(Input.mousePosition.x, Input.mousePosition.y); float dx = (float)0.8 * (p2.x - p1.x); float dy = (float)0.8 * (p2.y - p1.y); //鼠标左右移动 if (dx >= 0) { transform.Translate(-dx * Vector3.right * Time.deltaTime); } else { transform.Translate(dx * Vector3.left * Time.deltaTime); } //上下 移动 if (dy >= 0) { transform.Translate(dy * Vector3.down * Time.deltaTime); } else { transform.Translate(-dy * Vector3.up * Time.deltaTime); } } } private void zoom() { //通过鼠标滚轮实现场景缩放 //鼠标滚轮的效果 //Camera.main.fieldOfView 摄像机的视野 //Camera.main.orthographicSize 摄像机的正交投影 //Zoom out if (Input.GetAxis("Mouse ScrollWheel") < 0) { if (Camera.main.fieldOfView <= 100) Camera.main.fieldOfView += 2; if (Camera.main.orthographicSize <= 20) Camera.main.orthographicSize += 0.5F; } //Zoom in if (Input.GetAxis("Mouse ScrollWheel") > 0) { if (Camera.main.fieldOfView > 2) Camera.main.fieldOfView -= 2; if (Camera.main.orthographicSize >= 1) Camera.main.orthographicSize -= 0.5F; } } private void rotate() { if (Input.GetKey(KeyCode.C)) { transform.Rotate(0, 0, -25 * Time.deltaTime, Space.Self); } if (Input.GetKey(KeyCode.Z)) { transform.Rotate(0, 0, 25 * Time.deltaTime, Space.Self); } //通过鼠标X坐标拖动场景 if (Input.GetMouseButtonDown(1)) { //鼠标左键按下时记录鼠标位置p1 p3 = new Vector2(Input.mousePosition.x, Input.mousePosition.y); } if (Input.GetMouseButton(1)) { //鼠标左键拖动时记录鼠标位置p2 p4 = new Vector2(Input.mousePosition.x, Input.mousePosition.y); float dx = (float)0.8 * (p4.x - p3.x); float dy = (float)0.8 * (p4.y - p3.y); if (dx >= 0) { transform.Rotate(0, 0, -25 * Time.deltaTime, Space.Self); } else { transform.Rotate(0, 0, 25 * Time.deltaTime, Space.Self); } //上下 移动 if (dy >= 0) { transform.Rotate(0, 0, -25 * Time.deltaTime, Space.Self); } else { transform.Rotate(0, 0, 25 * Time.deltaTime, Space.Self); } } }