Unity 沿 X 轴移动播放器

Unity Moving Player along X-axis

我正在尝试根据手指位置创建玩家沿 x 轴的移动。

我需要发生的事情: 不是多点触控。我想要它,这样玩家就可以放下一根手指并抓住那个位置。然后检查玩家是否在 x 轴上沿着屏幕拖动手指,并根据他们从第一次触摸拖动手指的位置向左或向右移动玩家。

因此,如果他们触摸屏幕并向左拖动:按速度向左移动,如果变为向右拖动,则按速度向右移动。

任何帮助都会很棒。

使用此答案中提供的代码@programmer:

您可以轻松检测到您所在的方向 swiping/dragging。替换调试

 void OnSwipeLeft()
{
    Debug.Log("Swipe Left");
}

void OnSwipeRight()
{
    Debug.Log("Swipe Right");
}

具有移动角色的功能。如果你使用 RigidBody 来移动你的角色,你可以使用 https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html。如果它是普通物体,您可以通过调整 transform.position 来移动它。

如果您需要有关如何移动 rigidbody\normal 对象的更多信息,请告诉我您的游戏类型以及有关如何设置播放器的更多详细信息。

最简单的方法是存储第一个触摸位置,然后将 X 与该位置进行比较:

public class PlayerMover : MonoBehaviour
{
    /// Movement speed units per second
    [SerializeField]
    private float speed;

    /// X coordinate of the initial press
    // The '?' makes the float nullable
    private float? pressX;



    /// Called once every frame
    private void Update()
    {
        // If pressed with one finger
        if(Input.GetMouseButtonDown(0))
            pressX = Input.touches[0].position.x;
        else if (Input.GetMouseButtonUp(0))
            pressX = null;


        if(pressX != null)
        {
            float currentX = Input.touches[0].position.x;

            // The finger of initial press is now left of the press position
            if(currentX < pressX)
                Move(-speed);

            // The finger of initial press is now right of the press position
            else if(currentX > pressX)
                Move(speed);

            // else is not required as if you manage (somehow)
            // move you finger back to initial X coordinate
            // you should just be staying still
        }
    }


    `
    /// Moves the player
    private void Move(float velocity)
    {
        transform.position += Vector3.right * velocity * Time.deltaTime;
    }

}

警告:此解决方案仅适用于具有可用触摸输入的设备(因为 Input.touches 使用)。