Considering I have four variables
event binded to each arrow key
, that can be 0
or 1
My current approach to this issue is simply 8 nested ifs checking each combination or keys
Is there a more math-y clever way to solve this issue?
Considering I have four variables
event binded to each arrow key
, that can be 0
or 1
My current approach to this issue is simply 8 nested ifs checking each combination or keys
Is there a more math-y clever way to solve this issue?
Given 4 variables up
left
down
right
with values zero or one, the simplest method is to define a 2-component direction vector (dx, dy)
like so:
dx = right - left
dy = up - down
(No conditionals required!)
If you need more specialized logic/behaviour for each direction, I'd be inclined to do something like...
directionIndex = 3 * (up - down) + right - left;
Then the directions shake out like so:
-4 down-left
-3 down
-2 down-right
-1 left
0 center / canceling
1 right
2 up-left
3 up
4 up-right
If you store an array of 9 direction vectors, you can add 4 to the index above to look up into your (zero-based) array, getting your direction in a single table lookup, again branch-free.
Or you could use this index as the control for a single switch-case statement, to do unique actions for each direction without more than one level of nesting. (Since I see you're asking about LÖVE, you can use a Lua analog of a switch like this)
A common method is to combine the opposite direction keys into a single axis, giving you X and Y movements, then you combine the X and Y into a single 2D movement vector.
Here's what that code might look like:
local dx,dy = 0,0
if (keyPressed.up) then dy = dy - 1 end
if (keyPressed.down) then dy = dy + 1 end
if (keyPressed.left) then dx = dx - 1 end
if (keyPressed.right) then dx = dx + 1 end
You need to decide a few things from here:
This method has the advantage of being adaptable across different input devices. Gamepads for example will give you analog stick input as X and Y values between -1 and 1.
The code here is not too bad but still seems repetitive - there are four virtually identical if
conditions. But you'll see a lot of code like this when dealing with 2D (or 3D) problems. It's possible to refactor this code to have less repetition but there's a tradeoff between math-heavy code that's non-obvious. You need to decide whether having less repetitive code that's harder to understand is worth it.