2016-10-04 75 views
0

使用触摸输入我知道如何拖动一个游戏对象。但是我需要做的是(释放拖动时)检查拖动的速度并让对象进一步移动。因此,如果我快速拖动对象并将其释放,它将在释放后沿着拖动的方向移动一点。现在它只是停留在我移开手指的位置。任何人都知道这是如何完成的?Unity ios拖动宽松

我现在拥有的是:

 private Vector3 dist, distEnd; 
     float posX; 
     float posY; 

    void OnMouseDown() { 

      dist = Camera.main.WorldToScreenPoint (transform.position); 
      posX = Input.mousePosition.x - dist.x; 
      posY = Input.mousePosition.y - dist.y; 


     } 

     void OnMouseDrag() 
     { 
      Vector3 curPos = new Vector3 (Input.mousePosition.x - posX, Input.mousePosition.y - posY, dist.z); 
      Vector3 worldPos = Camera.main.ScreenToWorldPoint (curPos); 
      transform.position = worldPos; 

     } 

     void OnMouseUp() { 
      distEnd = Camera.main.WorldToScreenPoint (transform.position); 


     } 

然后我添加了一个RigidBody2d对象 - 尝试添加力 - 但我想我需要计算的速度和阻力/鼠标的方向 - 前我可以添加定向力给对象?

GetComponent<Rigidbody2D>().AddForce (Vector2 (FORCE_DIRECTION_X, FORCE_DIRECTION_Y)); 

但是我很难计算方向和速度的阻力。

任何帮助表示赞赏!

谢谢。

+0

我们当然知道,但你可以给为您的样品代码作为答案的基础? –

+0

对不起,这里是我到目前为止的代码。 –

回答

0

对,我终于找到了答案:-)我已经包含了一个供其他人使用的脚本(尽管我没有提出解决方案)。

也许有人会使用它,以及 - 改变变量“SmoothTime”,所以设定的时间之前拖速度为0

using UnityEngine; 
using System.Collections; 

public class dragMap : MonoBehaviour { 


private Vector3 _screenPoint; 
private Vector3 _offset; 
private Vector3 _curScreenPoint; 
private Vector3 _curPosition; 
private Vector3 _velocity; 
private bool _underInertia; 
private float _time = 0.0f; 
public float SmoothTime = 2; 
void Update() 
{ 
    if(_underInertia && _time <= SmoothTime) 
    { 
     transform.position += _velocity; 
     _velocity = Vector3.Lerp(_velocity, Vector3.zero, _time); 
     _time += Time.smoothDeltaTime; 
    } 
    else 
    { 
     _underInertia = false; 
     _time = 0.0f; 
    } 
} 
void OnMouseDown() 
{ 
    _screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); 
    _offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPoint.z)); 
    //Screen.showCursor = false; 
    _underInertia = false; 
} 
void OnMouseDrag() 
{ 
    Vector3 _prevPosition = _curPosition; 
    _curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, _screenPoint.z); 
    _curPosition = Camera.main.ScreenToWorldPoint(_curScreenPoint) + _offset; 
    _velocity = _curPosition - _prevPosition; 
    transform.position = _curPosition; 
} 
void OnMouseUp() 
{ 
    _underInertia = true; 
    //Screen.showCursor = true; 
} 

}