1
\$\begingroup\$

I have a problem with the Unity game engine. I am making an Android game. I want to move an object by a small distance every time the user taps the screen, but not when the user holds the screen.

This is my current code. When the user holds the screen, the object keeps moving. I want to only move the object once the user touches the screen and not move it again until they released it:

void Update () {
        if (Input.touchCount > 0) {
            transform.position = new Vector2(transform.position.x, transform.position.y+0.1f);
        }
\$\endgroup\$
  • \$\begingroup\$ Your question was very hard to read. I rewrote it in proper English. Please say if I understood it correctly. \$\endgroup\$ – Philipp Mar 19 '17 at 11:24
2
\$\begingroup\$

Why not use touch phase that is built into unity via the Touch class?

void Update () {
    foreach (Touch finger in Input.touches)
    {
        if (finger.phase == TouchPhase.Began)
        {
            transform.position = new Vector2(transform.position.x, transform.position.y+0.1f);
        }
    }
}

This will check if the a finger has been detected and will move the object in the same way as the original code did, except the finger must have just been detected on the screen. If it is held the Touch Phase will change from Begin to either Moved or Stationary.

You might also want to look at tap count if you need to check if the user is repeatedly tapping on screen.

Hope this helps

\$\endgroup\$
  • \$\begingroup\$ @Jam When this answer solved your problem, please accept it by clicking on the checkmark-icon next to it. \$\endgroup\$ – Philipp Mar 20 '17 at 14:51

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.