Double Tap
To make a button that reacts on double tap, you basically need a timer that starts when you push a button. If you push the button again while the timer runs, you perform a double tap. Otherwise it is counted as 2 single taps.
The following code should be placed in the TouchPhase.began code.
Let's first make 3 variables. A boolean called oneTap, a float called doubleClickTimer and a float called delay. I made them all public so I can easily check and edit them in the Inspector.
In your Touchphase.began you check if the button is not tapped, if that's the case set oneTap to true. If that's not the case, run the logic for the double tap.
If the button is tapped increase doubleClickTimer every frame. If it's equal to the delay, set one tap false (the double tap failed because you ran out of time). :
And There you have it. A button that reacts to a double tap.
public bool oneTap; public float doubleClickTimer; public float delay;
In your Touchphase.began you check if the button is not tapped, if that's the case set oneTap to true. If that's not the case, run the logic for the double tap.
if (!oneTap) { oneTap = true; } else { #put logic for double tap here# }
If the button is tapped increase doubleClickTimer every frame. If it's equal to the delay, set one tap false (the double tap failed because you ran out of time). :
if(oneTap) { doubleClickTimer++; if(doubleClickTimer >= delay ) { oneTap = false; doubleClickTimer = 0; } }
And There you have it. A button that reacts to a double tap.
Tap and hold
For tap and hold you also need a timer. But this time the timer starts running when you tap and hold the button. To achieve this you need to put this in the TouchPhase.stationary part of your touch code.
For this effect we need two variables of type int. 'holding' is the time you are holding the button and 'holdTime' is the max time you need to hold the button for logic to activate.
Then in the TouchPhase.Stationary code you check if holding is more or equal to holdTime. If that's true, you do the tap and hold logic, otherwise you increase the holding timer.:public int holding;
public int holdTime;
if (holding >= holdTime) { #do tap and hold things# } else { holding++; }
Toggle
For toggling a button there is a pretty nifty trick you can do that I didn't know about at first.
But first we make a variable with type boolean called buttonActivated
public bool buttonActivated;Then when you press that button, or other object for that matter you set the buttonActivated bool to !buttonActivated. Like this:
if (hit.transform.name == "Toggle") { buttonActivated = !buttonActivated; }(In this example I checked for the name to be "Toggle". Feel free to check for something else).
Geen opmerkingen:
Een reactie posten