Reputation: 491
I am attempting to use keyboard input to translate a label around the screen. Currently only down and left are functioning. My code is below.
debug = true
down = 0
up = 0
left = 0
right = 0
text = 'non'
x = 100
y = 100
dx = 0
dy = 0
function love.load(arg)
end
function love.update(dt)
if love.keyboard.isDown('escape') then
love.event.push('quit')
end
if up == 1 then
dy = -1
end
if up == 0 then
dy = 0
end
if down == 1 then
dy = 1
end
if down == 0 then
dy = 0
end
if right == 1 then
dx = 1
end
if right == 0 then
dx = 0
end
if left == 1 then
dx = -1
end
if left == 0 then
dx = 0
end
end
function love.keypressed(key)
if key == 'up' or key == 'w' then
text = 'up'
up = 1
end
if key == 'down' or key == 's' then
text = 'down'
down = 1
end
if key == 'right' or key == 'd' then
text = 'right'
right = 1
end
if key == 'left' or key == 'a' then
text = 'left'
left = 1
end
end
function love.keyreleased(key)
text = 'non'
if key == 'up' or key == 'w' then
up = 0
end
if key == 'down' or key == 's' then
down = 0
end
if key == 'right' or key == 'd' then
right = 0
end
if key == 'left' or key == 'a' then
left = 0
end
end
function love.draw(dt)
x = x + dx
y = y + dy
love.graphics.print(text, x, y)
end
Experimentation has shown that the order of if statements in the love.update(dt) section effects which directions work but I cannot get all four to work at the same time.
Upvotes: 2
Views: 1309
Reputation: 57
change love.update and love.draw to something like this:
function love.update(dt)
if love.keyboard.isDown('escape') then
love.event.push('quit')
end
dx, dy = 0
if up == 1 then
dy = -1
end
if down == 1 then
dy = 1
end
if right == 1 then
dx = 1
end
if left == 1 then
dx = -1
end
x = x + dx
y = y + dy
end
function love.draw(dt)
love.graphics.print(text, x, y)
end
when you check for input, you properly assigns them the values if it is true that the button is pressed, but you also check if the button is NOT pressed and then un-assign the value. so if up was pressed, the check for down not being pressed immediately overwrites the value assigned. also you may want to scale dx and dy by the dt value depending on your target fps (if you're not using fixed timestep that is, to make the speed of movement the same regardless of the a machine's FPS).
Upvotes: 1