拖动以统一移动并按住触摸以保持同一方向移动

问题描述

所以我试图编写一个代码来通过在屏幕上拖动来移动玩家,但我希望玩家在我握住手指时保持同一个方向移动,只有在我拿开手指时才停止。 我写了这段代码,玩家移动但当我握住手指时它会停止。

void Update()
{
    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Moved)
        {
            transform.position = new Vector3(
                transform.position.x + touch.deltaPosition.x * speedModifier,transform.position.y,transform.position.z + touch.deltaPosition.y * speedModifier);
        }
    }
}

解决方法

如果我理解正确,您可以存储最后的滑动动作并将其用于固定触摸,例如

Vector2 currentDirection;

void Update()
{
    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        switch (touch.phase)
        {
            case TouchPhase.Moved:
                currentDirection = touch.deltaPosition * speedModifier;
                transform.position += currentDirection;
                break;

           case TouchPhase.Stationary:
               transform.position += currentDirection;
               break;

           default:
               currentDirection = Vector2.zero; 
               break;
        }
    }
}

这样它就会以最后的滑动速度连续移动。

但是,通常您还应该考虑 Time.deltaTime 以与帧速率无关。

,

所以根据你的代码,我尝试了这个。但是当我按住触摸时,它要么移动得很慢,要么在一段时间后改变方向。有什么想法吗?

Vector3 currentDirection;

void Update()
{
    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);
        switch (touch.phase)
        {
            case TouchPhase.Moved:
                currentDirection = new Vector3(touch.deltaPosition.x,touch.deltaPosition.y) * speedModifier * Time.deltaTime;
                transform.position += currentDirection;
                break;

            case TouchPhase.Stationary:
                transform.position += currentDirection;
                break;

            default:
                currentDirection = Vector3.zero;
                break;
        }
    }
}