01 |
using UnityEngine; |
02 |
using System.Collections; |
03 |
04 |
public class NewBehaviourScript
: MonoBehaviour { |
05 |
06 |
private bool onDrag
= false ; //是否被拖拽 |
07 |
public float speed
= 3f; //旋转速度 |
08 |
private float tempSpeed; //阻尼速度 |
09 |
private float axisX; //鼠标沿水平方向移动的增量 |
10 |
private float axisY; //鼠标沿垂直方向移动的增量 |
11 |
private float cXY; //鼠标移动的距离 |
12 |
13 |
14 |
///
<summary> |
15 |
///
接收鼠标按下的事件 |
16 |
///
</summary> |
17 |
public void OnMouseDown() |
18 |
{ |
19 |
axisX
= 0f; //为移动的增量赋初值 |
20 |
axisY
= 0f; |
21 |
} |
22 |
23 |
///
<summary> |
24 |
///
鼠标拖拽时的操作 |
25 |
///
</summary> |
26 |
public void OnMouseDrag() |
27 |
{ |
28 |
onDrag
= true ; //被拖拽 |
29 |
axisX
= -Input.GetAxis( "Mouse
X" ); //获得鼠标增量 |
30 |
axisY
= Input.GetAxis( "Mouse
Y" ); |
31 |
cXY
= Mathf.Sqrt(axisX * axisX + axisY * axisY); //计算鼠标移动的长度 |
32 |
if (cXY
== 0f) |
33 |
{ |
34 |
cXY
= 1f; |
35 |
} |
36 |
} |
37 |
38 |
///
<summary> |
39 |
///
计算阻尼速度 |
40 |
///
</summary> |
41 |
///
<returns>阻尼的值</returns> |
42 |
public float Rigid() |
43 |
{ |
44 |
if (onDrag) |
45 |
{ |
46 |
tempSpeed
= speed; |
47 |
} |
48 |
else |
49 |
{ |
50 |
if (tempSpeed
> 0) |
51 |
{ |
52 |
tempSpeed
-= speed * 2 * Time.deltaTime / cXY; //通过除以鼠标移动长度实现拖拽越长速度减缓越慢 |
53 |
} |
54 |
else |
55 |
{ |
56 |
tempSpeed
= 0; |
57 |
} |
58 |
} |
59 |
return tempSpeed; //返回阻尼的值 |
60 |
} |
61 |
62 |
///
<summary> |
63 |
/// |
64 |
///
</summary> |
65 |
public void Update() |
66 |
{ |
67 |
gameObject.transform.Rotate( new Vector3(0,
axisX, 0) * Rigid(), Space.World); |
68 |
if (!Input.GetMouseButton(0)) |
69 |
{ |
70 |
onDrag
= false ; |
71 |
} |
72 |
} |
73 |
} |