【问题标题】:Drag to move at unity and hold touch to keep moving at same direction拖动以统一移动并按住触摸以保持相同方向移动
【发布时间】:2021-01-07 18:06:22
【问题描述】:

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

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

【问题讨论】:

  • 您的对象应该移动多快?朝哪个方向?如果您按住触摸,则不会有任何deltaPosition ;)

标签: c# unity3d mobile touch


【解决方案1】:

如果我理解正确,您可以存储最后一次滑动动作并将其用于静止触摸,例如

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 与帧速率无关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多