- Home /
The question is answered, right answer was accepted
Does Unity have a way of storing and comparing the last key pressed with the current one.
Im using a dash system based on wasd input
if (Input.GetKeyDown(KeyCode.W))
{
if ((Time.time - lastTapTime) < tapSpeed)
{
this.Trigger_FDodge();
Debug.Log("ForDodge");
}
lastTapTime = Time.time;
}
if (Input.GetKeyDown(KeyCode.D))
{
if ((Time.time - lastTapTime) < tapSpeed)
{
this.Trigger_RDodge();
Debug.Log("RightDodge");
}
lastTapTime = Time.time;
}
Any one of these on their own is fine, but, because I need to be able to dodge in four directions, I hit a problem. While strictly still a double tap, pressing 'W' then 'D' will trigger a dodge, when it should only be triggered with 'WW' or 'DD'.
When I used XNA, there were options for input states, so I could store and compare the last key pressed with the current one.
KeyboardState lastKeyboardState = KeyboardState;
Does Unity have a way of doing this?
Answer by gregzo · Aug 01, 2013 at 03:10 PM
No, but caching key presses should'nt be too hard...
declare
private KeyCode lastHitKey;
Then cache every keyboard input :
if (Input.GetKeyDown(KeyCode.W))
{
lastHitKey = KeyCode.W;
//your foo here
}
Or, more elegant as suggested in the comments, but afaik neeeds to be in OnGUI and not Update :
if ( Input.anyKeyDown )
{
lastHitKey == Event.current.keyCode;
}
You can then check if a key is the same as lastHitKey.
Event.current.keyCode will get you the current key without having to check every single option :)
It seems to working here if (lastHit$$anonymous$$ey == $$anonymous$$eyCode.W && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W)) { if ((Time.time - lastTapTime) < tapSpeed) { this.Trigger_FDodge(); Debug.Log("ForDodge"); } lastTapTime = Time.time; } if (lastHit$$anonymous$$ey == $$anonymous$$eyCode.D && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.D)) { if ((Time.time - lastTapTime) < tapSpeed) { this.Trigger_RDodge(); Debug.Log("RightDodge"); } lastTapTime = Time.time; } if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W)) { lastHit$$anonymous$$ey = $$anonymous$$eyCode.W; //your foo here } if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.D)) { lastHit$$anonymous$$ey = $$anonymous$$eyCode.D; //your foo here }
Thank you very much :) Any tips on tidying it up?
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Simultaneous button presses 2 Answers
How do I invert the Y axis in Penelope tutorial? 3 Answers