Checking if a key has been pressed twice in quick succession

Hi guys,

My game is 2.5d, you control one character, he can move left right and jump. The controls are WASD and Spacebar. What I’m trying to do is have it so that when the user presses DD or AA in quick succession it performs a dash (increases speed for about half a second)

So heres my current logic of the idea for D:

http://pastebin.com/igUWA8kg

thanks for any feedback

I really noticed the same effect as @benhacking mentioned in the comments, so I played around a little bit and found out a nice little solution.

        if(Input.GetKeyDown(KeyCode.A) && firstButtonPressed) {
			if(Time.time - timeOfFirstButton < 0.5f) {
				Debug.Log("DoubleClicked");
			} else {
				Debug.Log("Too late");
			}

			reset = true;
		}

		if(Input.GetKeyDown(KeyCode.A) && !firstButtonPressed) {
			firstButtonPressed = true;
			timeOfFirstButton = Time.time;
		}

		if(reset) {
			firstButtonPressed = false;
			reset = false;
		}

It is interesting how the order of the if-statements is critical for this solution to work.

It might not be the best implementation but this is pretty much the way I handle similar cases. I’ve wrote this for a dash and while its a little longer than I’d have expected, it works fairly well.

float maxDelay = 0.5f;
bool dashReady = false;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        if(dashReady)
            Dash();
        else
            PrepareDash(true);
    }
}

void Dash()
{
    dashReady = false;
    //dash action goes here
}

void PrepareDash(bool makeReady)
{
    //this is where the handling happens
    CancelInvoke("CancelDash");
    Invoke("CancelDash",maxDelay);
    dashReady = true;
}

void CancelDash()
{
    dashReady = false;
}

I would do this in a different way, (code not tested but should work):

public class MyBehaviour : MonoBehaviour {

	// Must double tap within half a second (by default)
	public float doubleTapTime = 0.5f;
	// Time to wait between dashes
	public float dashWaitTime = 2.0f;

	// Time that the dash button was last pressed
	private float _lastDashButtonTime;
	// Time of the last dash
	private float _lastDashTime;
	
	void Update() {
		if (isDashPossible && Input.GetKeyDown(KeyCode.D)) {
			// If second time pressed?
			if (Time.time - _lastDashButtonTime < doubleTapTime)
				DoDoubleDash();
			_lastDashButtonTime = Time.time;
		}
	}
	
	bool isDashPossible {
		get {
			return Time.time - _lastDashTime > dashWaitTime;
		}
	}
	
	void DoDoubleDash() {
		_lastDashTime = Time.time;
		
		// blah...
	}

}