Unity ios拖动缓动

时间:2016-10-04 08:00:48

标签: c# unity3d

使用Touch输入我知道如何拖动游戏对象。但我需要做的是(在释放拖动时)检查拖动的速度并使对象移动得更远。因此,如果我快速拖动对象并释放它,它将在释放后沿拖动方向移动一点。就像现在一样,它只是停在我移开手指的位置。有谁知道这是怎么做的?

我现在拥有的是:

        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));

但是我在计算方向和速度方面遇到了困难。

感谢任何帮助!

感谢。

1 个答案:

答案 0 :(得分:0)

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

也许有人也可以使用它 - 改变变量&#34; SmoothTime&#34;所以在拖曳速度为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;
}

}