Home > OS >  How to do a similar function to "Input.GetButtonUp" using the touch input in unity?
How to do a similar function to "Input.GetButtonUp" using the touch input in unity?

Time:08-03

I have this method on update, which makes the player move in a specific direction with an impulse:

 void Move()
{
    Vector3 dir = (rotatingPropellant.transform.position - transform.position).normalized;

    if (Input.GetButtonUp("Jump"))
    {
        playerRb.AddForce((dir * impulseForce * Time.deltaTime).normalized, ForceMode2D.Impulse);
    }


    if (touch.phase == TouchPhase.Ended )
    {
        playerRb.AddForce((dir * impulseForce * Time.deltaTime).normalized, ForceMode2D.Impulse);
    }

}

It works fine on PC when using "Input.GetButtonUp" because it returns a "true" value only once, but with "touch.phase == TouchPhase.Ended" the player keeps moving (I'm assuming because the value is true every frame), is there a way to mimic the one frame "true" value like "Input.GetButtonUp" ?

I tried adding a bool to the TouchPhase if statement and making it false after the impulse but it didn't work :( something like this:

 if (touch.phase == TouchPhase.Ended && !touched)
    {
        playerRb.AddForce((dir * impulseForce * Time.deltaTime).normalized, ForceMode2D.Impulse);
        touched = true;
    }

Maybe i should be addressing this in a different way?

CodePudding user response:

In order to check the phase of a touch, you need to get the touch first.

If you only want to track the first touch, then this code will work (also, I recommend using the TouchPhase.Began rather than TouchPhase.Ended, it is more intuitive for a user):

if (Input.touchCount > 0)
{
    Touch touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Began && !touched)
    {
        playerRb.AddForce((dir * impulseForce * Time.deltaTime).normalized, ForceMode2D.Impulse);
        touched = true;
    }
}

If you want to have the ability to manage multiple touches, you'll need to iterate through all finger touches and track them appropriately.

for (int i = 0; i < Input.touchCount;   i)
{
    if (Input.GetTouch(i).phase == TouchPhase.Began)
    {
        //Manage the individual touch
    }
}
  • Related