For this, I need more than a basic if-else due to priority : if I press "right" while "up" is already down, I'd want the sprite to go right, though depending on which keytest runs first, "right" is likely to be ignored, returning "up" instead, which is a problem.
So I thought about something like this :
Code: Select all
local last_direction
local directions = {"w","a","s","d"}
function love.keypressed(k)
for i, key in pairs(directions) do
if k == key then
last_direction = key
break
end
end
end
function love.update(dt)
if love.keyboard.isDown(directions) then
if love.keyboard.isDown(last_direction) then
move(last_direction)
else
--Test other keys in case last_direction got released while another one was still down
if love.keyboard.isDown("w") then
move("w")
end
--Run test for each other directions as well
end
end
end
function move(key)
--Move the sprite towards key's direction
end
So would this be good enough for a non-diagonal 2d control? Would there be a better way? If not, could I change anything to improve this code?
Thanks once more to anyone who will take the time to answer!