Search code examples
c#unity-game-enginetap

Long tap on the screen for character movement unity


i want to implement the long tap on the screen..If the user long taps on the screen the position of the x and y axis decreases and as soon as he releases the tap the x increases and the y decreases. i have messed around with somethings but no luck..heres the code i have been trying.

public class move : MonoBehaviour 
{
    public Vector2 velocity = new Vector2(40,40);
    public float forwardspeed=0.02f;
    Vector2 movement;
    // Use this for initialization
    void Start () 
    {
        Debug.Log("start+"+Input.touchCount);

        movement.x+=(forwardspeed);
        movement.y-=(forwardspeed);
        rigidbody2D.velocity = movement;
    }

    // Update is called once per frame
    void FixedUpdate () 
    {
        int i=0;
        while (i < Input.touchCount)
        {
            // Is this the beginning phase of the touch?
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                Debug.Log("input touch count"+Input.touchCount);
                //  rigidbody2D.gravityScale =0;
                movement.x+=(forwardspeed);
                movement.y+=(forwardspeed);
                rigidbody2D.velocity = movement;
            }
            else if (Input.GetTouch(i).phase == TouchPhase.Ended)
            {
                movement.x += (forwardspeed);
                movement.y -= (forwardspeed);
                rigidbody2D.velocity = movement;
            }
            ++i;
        }
    }
}

Solution

  • You can use Input.touchCount to do exactly what you need with very simple code.

    If you want some behavior to occur while the user is touching the screen, that means you want the behavior to occur while Input.touchCount is non-zero. For example,

    void FixedUpdate() {
        if(Input.touchCount > 0) { //user is touching the screen with one or more fingers
            //do something
        } else { //user is not currently touching the screen
            //do something else
        }
    }
    

    Specific to your code, you would want to set the character's velocity to some value while Input.touchCount is zero, and then set it to a different value while it's not zero.

    void FixedUpdate() {
        if(Input.touchCount > 0) {
            rigidbody2D.velocity = new Vector2(forwardspeed, forwardspeed);
        } else {
            rigidbody2D.velocity = new Vector2(forwardspeed, -forwardspeed);
        }
    }
    

    Note the negative sign in the else block. Instead of adding and subtracting values like you were doing before, we're just setting the velocity to +/- depending on the state.