触摸移动设备上的输入

时间:2017-08-11 12:39:02

标签: c# android unity5

我有这个脚本用于在移动设备上输入触摸。但它只激活一次,我需要它才能运行,直到我把手指从屏幕上移开

public float speed = 3;


public Rigidbody rb;
public void MoveLeft()
{
    transform.Translate(-Vector3.right * speed * Time.deltaTime);
}
public void StopMoving()
{
    rb.velocity = new Vector2(0, 0);
}

public void MoveRight()
{
    rb.velocity = new Vector2(-speed, 0);
}
private void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        float middle = Screen.width / 2;
        if (touch.position.x < middle && touch.phase == TouchPhase.Began)
        {
            MoveLeft();
        }
        else if (touch.position.x > middle && touch.phase == TouchPhase.Began )
        {
            MoveRight();
        }
    }
    else
    {
        StopMoving();
    }
}

}

1 个答案:

答案 0 :(得分:3)

您只需删除两个&& touch.phase == TouchPhase.Began部分即可。只要屏幕上有一个手指,这将使整个if语句评估为真。

private void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        float middle = Screen.width / 2;
        if (touch.position.x < middle)
        {
            MoveLeft();
        }
        else if (touch.position.x > middle)
        {
            MoveRight();
        }
    }
    else
    {
        StopMoving();
    }
}