0
\$\begingroup\$

I am trying to make my character jump when the player taps the screen.

At the moment it jumps when I press space bar, but how can I change the code to make him jump when the screen is tapped?

This code works as the character then jumps up:

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.gravityScale *= -1;
    }
}

This code using touch does not work: the character just stays where he is when I click the screen on my computer.

public void Update()
{
    if (Input.touchCount > 0)
    {
        Touch touch = Input.GetTouch(0);
        rb.gravityScale *= -1;
    }        
}
\$\endgroup\$
16
  • 1
    \$\begingroup\$ Make jump with which button? There are many types of buttons \$\endgroup\$ – Nick Apr 4 '20 at 14:45
  • \$\begingroup\$ Just one button on the entire screen similar to flappy bird. \$\endgroup\$ – Usmaan Mahmood Apr 4 '20 at 14:46
  • \$\begingroup\$ Presumably you considered using Input.touchCount to detect when the screen has been touched? \$\endgroup\$ – DMGregory Apr 4 '20 at 14:53
  • \$\begingroup\$ Please see above the input.touchcount I used as it still did not work. \$\endgroup\$ – Usmaan Mahmood Apr 4 '20 at 15:03
  • 1
    \$\begingroup\$ If you've solved your problem, please post your solution as an Answer below. \$\endgroup\$ – DMGregory Apr 4 '20 at 16:12
1
\$\begingroup\$

I changed the code to the following by adding a TouchPhase.Began to the if statement:

public void Update()
{


    if (Input.touchCount == 1)
    {
        if (Input.GetTouch(0).phase == TouchPhase.Began)
        {
            Touch touch = Input.GetTouch(0);

            rb.gravityScale *= -1;

        }
    }


}

Then testing it on a device using unity remote.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.