基于Touch(Unity)拖动相机

时间:2013-10-29 07:26:36

标签: android ios mobile touch unity3d

在我的游戏中,我希望相机根据用户滑动手指进行移动。我的问题是当有人从屏幕上移开他们的手指并再将其放下时,相机会跳到一个新的位置...我猜这与坐标有关,我这样说是因为如果我点击远离某个地方的地方我从屏幕上移开手指,相机跳了起来。这是代码:

 var speed : int = 1;

 var lastPoint : Vector2; //make this private if you want to.

 function Update()
 {

     var offset : float; //offset of the touch from last frame     

     if(Input.touches.Length  0)//make sure we have a touch in the first place
     {

          var evt : Touch = Input.touches[0];   //setting up touch events so we can get fancy.
          if(evt.phase == TouchPhase.Began)    //this is the first frame the screen has been touched for, simply save the point.
          {
               lastPoint == evt.position;
          }
          else if(evt.phase == TouchPhase.Moved
          {
              offset = evt.position.x - lastPoint.x ;//take the difference

              //I'm going to use Transform.Rotate because it's handy dandy

              transform.Rotate(0,offset * speed,0);

              //save the new "lastPoint"

              lastPoint = evt.position;
         }
         else if(evt.phase == TouchPhase.Ended)
         {
             //If you want the object to drift after you spin it you can make a function to go here.
             //To do this, take the speed of the rotation and continue to rotate all while subtracting off of the speed.
             //I would use the Transform.Rotate function on this too.
             //If you need me to I could write this function too.

         }
     }
 }

让相机恢复原状的解决方案是什么,一旦有人再次放下手指就不会跳转?

如果有更好的解决方案/解决问题的更有效方法,我也愿意重做它。

非常感谢!

1 个答案:

答案 0 :(得分:0)

提供的代码似乎很好,您需要做的就是当用户没有按下时,您每帧都更新lastPoint。或者,如果您知道用户何时开始按下,只需在计算偏移量之前将lastPoint设置为当前位置。这样,当用户触摸屏幕的第一帧时,偏移量为零。