How do I differentiate a button being held down from a simple press?
If I have a gamepad button or a keyboard key, is there a way where I can detect if the player is simply pressing on it vs. holding it?
An example is how, in Super Mario Odyssey, a button press will throw Mario's cap forward, and a button hold will keep it out for a few seconds. How can that sort of detection be done in Unity?
I understand that GetButton() tracks every frame the button is down, but it will still trigger GetButtonDown() at the very beginning, and I'm wondering if there's a way to avoid GetButtonDown() while still getting the hold effect from GetButton(). Is this possible? If not, what are workarounds that games like Mario Odyssey use to create different press/hold actions out of the same button?
Answer by Hellium · Jul 24, 2019 at 11:04 PM
The idea is to track the time while the button is held down and trigger an action according to the duration.
private float holdDuration;
private void Update()
{
if( Input.GetKey( KeyCode.Space ) )
{
holdDuration += Time.deltaTime ;
}
else if( Input.GetKeyUp( KeyCode.Space ) )
{
if( holdDuration < 0.2f )
{
Debug.Log( "Throw cap" );
}
else
{
Debug.Log( "Cap held, and thrown" );
}
holdDuration = 0;
}
}
If you want to prevent a button from being held too long:
public float MaxHoldDuration = 1;
public float QuickHoldDuration = 0.2f;
private float holdDuration;
private void Update()
{
if( Input.GetKeyDown( KeyCode.Space ) )
{
holdDuration = 0 ;
}
if( holdDuration >= 0 && Input.GetKey( KeyCode.Space ) )
{
holdDuration += Time.deltaTime ;
if( holdDuration >= MaxHoldDuration )
{
Debug.Log("Strongly throw the cap");
}
}
else if( Input.GetKeyUp( KeyCode.Space ) )
{
if( holdDuration < QuickHoldDuration )
Debug.Log( "Throw cap" );
else
Debug.Log("Strongly throw the cap");
holdDuration = -1;
}
}
Answer by crlycstl · Jul 24, 2019 at 11:04 PM
What about starting a timer when the user begins holding down the button, and then checking on GetButtonUp() whether the button was held down long enough to perform the held-down action?