Search code examples
unity-game-enginetouchgame-engine

Why does my TouchPhase.Began not work like this?


I don't understand why Input.GetTouch is not working here.

private void Update()
{
    Vector2 vel = rb.velocity;
    float ang = Mathf.Atan2(vel.y, x: 10) * Mathf.Rad2Deg;

    if (Input.GetKey(KeyCode.Space))
    {
        rb.AddForce(Vector2.up * gravity * Time.deltaTime * 2000f);
    }
    if (Input.GetTouch(TouchPhase.Began))
    {
        rb.AddForce(Vector2.up * gravity * Time.deltaTime * 2000f);
    }
}

Solution

  • Input.GetTouch expects an index .. you are passing in an enum value.

    The API actually has a couple of examples how to use touch in Unity.

    In your case you only want to check if there is a first touch in the state Began so you can use e.g.

    private void Update () {
        Vector2 vel = rb.velocity;
        float ang = Mathf.Atan2 (vel.y, x : 10) * Mathf.Rad2Deg;
    
        if (Input.GetKey (KeyCode.Space)) {
            rb.AddForce (Vector2.up * gravity * Time.deltaTime * 2000f);
        }
    
        if(Input.touchCount > 0)
        {
            if (Input.GetTouch(0).phase == TouchPhase.Began) 
            {
                rb.AddForce (Vector2.up * gravity * Time.deltaTime * 2000f);
            }
        }
    }