Execute one key input at a time at snake game preventing opposite direction

Hey guys, just starting to learn blueprints and I searched all over and haven’t been able to find a solution to my issue (feeling myself stupid), hopefully you can help me.

So I’m doing a simple snake game with 4 action keys responsible for the snake’s directions, and the snake moves (through Add Actor World Offset) with each tick (I’ve set ticking to 0,25) - for example, when W is pressed, it would check through the branch whether the snake is moving in X axis and, if not, it would set snake to move up next tick, same with the other ones. However, I have faced an issue: the snake can move in opposite direction if I press 2 buttons simultaneously or in quick succession: for example, if, going up, I press the left button and then simultaneously the down button (all in-between ticks, it seems), at the next tick the snake will move down and not first left and only then down, thus the head will collide with its tail and the game will end.

So is there a way to put some input buffer or something else to prevent the head going in opposite direction and what is the best way to do so? Thanks in advance!

i suppose there is endless ways to solve this problem, what is best will depend on how it fits into your project, but here is one idea:

make a custom event called something like “input cooldown” that will set a retriggerable delay. After the delay, set a boolean to true. Call it something like “bIsReadyForInput.”

Then before each input events logic fires, check that the boolean is true. If it is, set the boolean to false, do the input logic, and then call the event input cooldown.

That’s a very simple thing that may be fine for a small project. If you find yourself getting overwhelmed with lots of conditional checks like that its probably better to look into refactoring the code completely, but that’s a bigger topic. If you want to get some more ideas for that sort of thing, I’ve found this book to be very helpful:
Game Programming Patterns

1 Like

Hey, tried it iut now and it works great, thanks so much!
And thanks for the book link, will be sure to check it :wink:

1 Like