So, I’ve got a fighting game with some pretty tight input windows, and I’d like to buffer the inputs for a few frames.
Basically, if the fighter is in the neutral state, pressing attack should lead into an attack. It uses Input.GetButtonDown(“attack”) to get the button, and if it detects a press, transitions into attacking state.
Now, let’s suppose the fighter has just landed, and ends up hitting “attack” a few frames before the land animation ends and he transitions back into neutral. As of right now, nothing would happen, since he’s not in the neutral state where the check is, and when he enters the state, the button press is no longer happening.
Is there a way to store inputs for a few frames, so that I can read a button press a few frames back? So, instead of using Input.GetButtonDown(“attack”), it’d be something like InputBuffer.KeyBuffered(“attack”,12) to see if the button was pressed within 12 frames?
The example above is just a bit of a simplification, I know for the above situation I could just use GetButton instead of GetButtonDown, but for a fighting game, you can imagine that the necessary inputs to buffer would get significantly more complicated.
There is no built in mechanism for this that I’m aware of, but I’ve done similar things in the past by having a class run on the update and check the inputs you’re looking for, when you get the inputs store a value to mark that input as triggered, and mark its time (either in actual time or frames). Then every update when you’re done checking inputs you look over all the listed inputs, anything that is older than say X frames, or X milliseconds you flag as not being triggered. Essentially giving you the ability to then ask the class.
Was button X pressed in the last Y frames?
You can also then reset the “triggered” flag if when one of your other scripts acts on that input, essentially consuming it if you needed to.
Hope this solution makes sense and can get you started.
To buffer the inputs, just create a variables like attackPressed and set them to true if specific keys are pressed. When you do your logic, check the variables and if they are valid, do what you have to do and do not forget to set them to their default state again. Here is an example.
bool jump;
public bool doTheMagic; //This can be set from outside
void Update () {
if (Input.GetKeyDown(KeyCode.j))
jump = true;
if (doTheMagic && jump) {
jump = false;
//Do your magic
}
}