JtBing
JtBing

Reputation: 53

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

}

Upvotes: 0

Views: 115

Answers (1)

ryeMoss
ryeMoss

Reputation: 4333

You simply need to remove the two && touch.phase == TouchPhase.Began portions. This will have the overall if-statement evaluate true as long as there is one finger on the screen.

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

Upvotes: 3

Related Questions