团结-拖动停止后继续物体惯性吗?

时间:2019-04-11 21:23:26

标签: c# unity3d physics

好,所以我有一个对象,可以控制在Unity中使用Mousedown的旋转,如下所示:

使用UnityEngine; 使用System.Collections;

public class ObjectRotator : MonoBehaviour
{

    private float _sensitivity;
    private Vector3 _mouseReference;
    private Vector3 _mouseOffset;
    private Vector3 _rotation;
    private bool _isRotating;

    void Awake()
    {
        _sensitivity = 0.4f;
        _rotation = Vector3.zero;

    }


    //This include 
    void Update()
    {
        if (_isRotating)
        {

            // offset
            _mouseOffset = (Input.mousePosition - _mouseReference);

            // apply rotation
            _rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity;

            // rotate
            transform.Rotate(_rotation);

            // store mouse
            _mouseReference = Input.mousePosition;
        }

    }



    void OnMouseDown()
    {
        EndiTweens();
        // rotating flag
        _isRotating = true;

        // store mouse
        _mouseReference = Input.mousePosition;
    }

    void OnMouseUp()
    {
        // rotating flag
        _isRotating = false;
    }

}

这很好用,除了在OnMouseUp()之后,该对象停止为止。我希望它像惯性一样“滑动”一点。我该如何实施?

尝试将其控制为停止值:

 //This include 
    void Update()
    {
        if(_isRotating && _isStopping)
        {
            // apply rotation
            t += Time.deltaTime * 1.1f;
            float rotDiff = Mathf.Lerp(2f, 0f, t); //some max
            _rotation.y = transform.rotation.y - rotDiff;


            print(_rotation.y);
            transform.Rotate(_rotation);

            if(t >= 1f)
            {
                _isRotating = false;
                _isStopping = false;
                t = 0f;
            }
        }
        else if (_isRotating)
        {

            // offset
            _mouseOffset = (Input.mousePosition - _mouseReference);

            // apply rotation
            _rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity;

            // rotate
            transform.Rotate(_rotation);

            // store mouse
            _mouseReference = Input.mousePosition;
        }

    }

    void EndiTweens()
    {
        iTween[] tweens = GetComponents<iTween>();
        foreach (iTween tween in tweens)
        {
            tween.time = 0;
            tween.SendMessage("Update");
        }

    }

    void OnMouseDown()
    {
        EndiTweens();
        // rotating flag
        _isRotating = true;

        // store mouse
        _mouseReference = Input.mousePosition;
    }

    void OnMouseUp()
    {
        // rotating flag
        _isStopping = true;
       _isRotating = false;
    }

1 个答案:

答案 0 :(得分:1)

OnMouseUp,您正在设置_isRotating = false。不要将此标志设置为false。添加另一个标志_isStopping,并计算每帧上降低的旋转速度。将最低速度设置为0.001,然后将速度设置为0或设置_isRotating = false