实现Unity编辑器模式下的旋转

  最近在做一个模型展示的项目,我的想法是根据滑动屏幕的x方向差值和Y方向的差值,来根据世界坐标下的X轴和Y轴进行旋转,但是实习时候总是有一些卡顿。在观察unity编辑器下的旋转之后,发现编辑器下的旋转非常流畅。仔细观察之后发现unity编辑器下的旋转运算模式如下图所示,红色箭头方向为触控滑动方向,黑色箭头为模型旋转的轴。 

  了解原理之后就是实现相关功能,具体实现还是粘代码吧。代码如下

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.UI;
 5 using UnityEngine.EventSystems;
 6 
 7 //脚本挂在Modelshow GameObject下
 8 public class ModelViewControl : MonoBehaviour {
 9     private bool isClick = false;
10     private Vector3 startPos;       //点下开始位置
11     private Vector3 endPos;         //点下终点位置
12     private float Move_X;           //x方向上的移动距离
13     private float Move_Y;           //Y方向上的移动距离
14 
15     //回调间距
16     float interval = 0.01f;
17     float clickBeginTime = 0.0f;
18     //模型引用
19     private Transform model;    //模型根节点
20     void Start () {
21         model = transform;
22       
23     }
24     // Update is called once per frame
25     void Update () {
26 #if UNITY_STANDALONE_WIN
27         if (Input.GetMouseButtonDown(0))
28 #elif UNITY_ANDROID
29         if(Input.touchCount > 0 && !isClick) 
30 #endif
31         {
32             isClick = true;
33 #if UNITY_STANDALONE_WIN
34             startPos = Input.mousePosition;
35 #elif UNITY_ANDROID
36             startPos = Input.touches[0].position;
37 #endif
38             clickBeginTime = Time.time;
39         }
40 #if UNITY_STANDALONE_WIN
41         if (Input.GetMouseButtonUp(0))
42 #elif UNITY_ANDROID
43         if (Input.touchCount == 0 && isClick)
44 #endif
45         {
46             isClick = false;
47         }
48         if (isClick && (Time.time - clickBeginTime) > interval)
49         {
50 #if UNITY_STANDALONE_WIN
51             endPos = Input.mousePosition;
52 #elif UNITY_ANDROID
53             endPos = Input.touches[0].position;
54 #endif
55             if ((endPos - startPos).magnitude < 5)
56             {
57                 return;
58             }
59             if(Mathf.Abs(endPos.x - startPos.x) < 5)
60             {
61                 endPos.x = startPos.x;
62             }
63             if (Mathf.Abs(endPos.y - startPos.y) < 5)
64             {
65                 endPos.y = startPos.y;
66             }
67             RotateModel(startPos,endPos);
68             startPos = endPos;
69         }
70     }
71     void RotateModel(Vector3 startPos , Vector3 endPos)
72     {
73         Vector3 direction = endPos - startPos;
74         Vector3 world_axis = Vector3.Cross(direction, Vector3.forward);
75         model.Rotate(world_axis.normalized, direction.magnitude * 0.3f, Space.World);
76     }
77 }

  因为这个项目是PC,但是我是做手机游戏的,写个什么程序都想在手机上跑一跑,因此有比较乱的平台编译宏,主要实现为获得滑动的方向,就相当于在世界坐标下的xoy面的上的一个向量,求direction与z轴所成的面的法向量,求得的法向量就是本次旋转的轴。再根据滑动的距离来设置相应的角度。项目传到了github。有需要的小伙伴自取https://github.com/gaoxu1994/RotateForUnity

 

posted @ 2017-03-22 16:13  Ending结局  阅读(1391)  评论(0编辑  收藏  举报