Author Topic: How to implement LongPress?  (Read 4751 times)

Shifty Geezer

  • Full Member
  • ***
  • Thank You
  • -Given: 7
  • -Receive: 9
  • Posts: 226
    • View Profile
How to implement LongPress?
« on: October 09, 2014, 09:30:04 AM »
I've been using OnPress() events for button IO. I now want a long-press, so if the button is held down for longer than a period of time, something happens.

I can use a timer started by OnPress() and on update, accumulate time since it was pressed and test against a threshold. This works except it doesn't register a movement off the button/touch place as a cancel, so a user can press a button, move their finger elsewhere, and the hold still triggers.

How can I test if the finger hasn't moved off the button after touch down?

Note I'm not just using this with buttons with colliders, but also the whole level to set points on the map. In effect, the whole screen is a UI.
« Last Edit: October 09, 2014, 09:41:23 AM by Shifty Geezer »

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: How to implement LongPress?
« Reply #1 on: October 10, 2014, 02:27:52 AM »
  1. void OnPress (bool isPressed)
  2. {
  3.     if (isPressed) Invoke("LongPress", 2f);
  4.     else CancelInvoke("LongPress");
  5. }
  6.  
  7. void OnDragOut () { CancelInvoke("LongPress"); }
  8.  
  9. void LongPress ()
  10. {
  11.     Debug.Log("Long press!");
  12. }
« Last Edit: April 01, 2015, 11:27:40 PM by ArenMook »

UNSH

  • Newbie
  • *
  • Thank You
  • -Given: 1
  • -Receive: 0
  • Posts: 5
    • View Profile
Re: How to implement LongPress?
« Reply #2 on: April 01, 2015, 06:52:33 AM »
For anybody else arriving here. I had to stop the coroutine with strings or the stopcoroutine wouldn't work. My knowledge of coroutines isn't deep enough to give the why's or even if it's good practice, but here you go.

  1. void OnPress (bool isPressed)
  2. {
  3.     if (isPressed) StartCoroutine("LongPress");
  4.     else StopCoroutine("LongPress");
  5. }
  6.  
  7. void OnDragOut () { StopCoroutine("LongPress"); }
  8.  
  9. IEnumerator LongPress ()
  10. {
  11.     yield return new WaitForSeconds(2f);
  12.     Debug.Log("Long press!");
  13. }
  14.  
  15.  

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: How to implement LongPress?
« Reply #3 on: April 01, 2015, 11:28:05 PM »
Old post! I've actually modified it to use Invoke instead since it's more suitable.