【狼】unity 鼠标拖拽物体实现任意角度自旋转

主要涉及函数

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 }

 

 

posted @ 2014-06-27 09:17  战狼96  阅读(6431)  评论(0编辑  收藏  举报