主要涉及函數
Input.GetAxis(“Mouse x”) 可取得鼠標橫向(x軸)移動增量
Input.GetAxis(“Mouse y”) 可取得鼠標豎向(y軸)移動增量
通過勾股定理獲取拖拽長度,長度越長旋轉越快
在project setting--Input 可以設置
直接上代碼,看了就明白了
1 using UnityEngine; 2 using System.Collections; 3 4 public class startRoate : MonoBehaviour 5 { 6 private bool onDrag = false; //是否被拖拽// 7 public float speed = 6f; //旋轉速度// 8 private float tempSpeed; //阻尼速度// 9 private float axisX = 1; 10 //鼠標沿水平方向移動的增量// 11 private float axisY = 1; //鼠標沿豎直方向移動的增量// 12 private float cXY; 13 void OnMouseDown() 14 { 15 //接受鼠標按下的事件// 16 17 axisX = 0f; axisY = 0f; 18 } 19 void OnMouseDrag() //鼠標拖拽時的操作// 20 { 21 22 onDrag = true; 23 axisX = -Input.GetAxis("moveX"); 24 //獲得鼠標增量// 25 axisY = Input.GetAxis("moveY"); 26 cXY = Mathf.Sqrt(axisX * axisX + axisY * axisY); //計算鼠標移動的長度// 27 if (cXY == 0f) { cXY = 1f; } 28 29 } 30 float Rigid() //計算阻尼速度// 31 { 32 if (onDrag) 33 { 34 tempSpeed = speed; 35 } 36 else 37 { 38 if (tempSpeed > 0) 39 { 40 tempSpeed -= speed * 2 * Time.deltaTime / cXY; //通過除以鼠標移動長度實現拖拽越長速度減緩越慢// 41 } 42 else { 43 tempSpeed = 0; 44 } 45 } 46 return tempSpeed; 47 } 48 49 void Update() 50 { 51 // this.transform.Rotate(new Vector3(axisY, axisX, 0) * Rigid(), Space.World); //這個是是按照之前方向一直慢速旋轉 52 if (!Input.GetMouseButton(0)) 53 { 54 onDrag = false; 55 this.transform.Rotate(new Vector3(axisY, axisX, 0)*0.5f, Space.World); 56 } 57 } 58 }