Unity沿X轴移动播放器

sha*_*ane 4 c# touch unity-game-engine

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

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

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

任何帮助都是极好的.

Tom*_*das 7

最简单的方法是存储第一个触摸位置,然后将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;
    }

}
Run Code Online (Sandbox Code Playgroud)

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