简体   繁体   English

移动设备上的触摸输入

[英]Touch input on mobile device

I have this script for inputting touches on the mobile device. 我有此脚本用于在移动设备上输入触摸。 But it activates only once, I need it to be run until I take my finger off the screen 但是它只能激活一次,我需要运行它直到我将手指从屏幕上移开

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

} }

You simply need to remove the two && touch.phase == TouchPhase.Began portions. 您只需要删除两个&& touch.phase == TouchPhase.Began部分。 This will have the overall if-statement evaluate true as long as there is one finger on the screen. 只要屏幕上有一根手指,这将使总体if语句评估为true。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM