take – How do I use hump.timer in a repeat loop in LOVE2D?

Question:

I'm asking this to make something move in LOVE2D when a key is pressed.

I've already tried

repeat
    imgx = imgx + 1
    timer.after(0, function() end)
until not love.keyboard.isDown('left')

but it did not work. Please help me!

Integer code:

function love.load()
    timer = require 'hump.timer'
    face = love.graphics.newImage("face.png")
    imgx = 0
    imgy = 0
end

function love.keypressed(key)
    if key == 'left' then
        repeat
            imgx = imgx + 1
            timer.after(0, function() end)
        until not love.keyboard.isDown('left')
    end
end

function love.update(dt)
    timer.update(dt)
end

function love.draw()
    love.graphics.draw(face, imgx, imgy)
end

Answer:

I recommend not using native loop to change the x coordinate of the image. I call this synchronous working. While this loop executes, the program will be stopped (but imgx will still change).

(If you get used to running timer#after in loops without yields to do something in the future it will end up creating problems.)

I don't think the problem has anything to do with it, anyway.

Try using Timer#every (ps: I don't know if that solves the problem as I don't know LOVE2D well):

function love.load()
    timer = require 'hump.timer'
    face = love.graphics.newImage 'face.png'
    imgx = 0
    imgy = 0
end

local function tick()
    imgx = imgx + 1;
    return love.keyboard.isDown 'left';
end

function love.keypressed(key)
    if key == 'left' then
        timer.every(.1, tick); -- atraso: 100 milisegundos
    end
end

function love.update(dt)
    timer.update(dt)
end

function love.draw()
    love.graphics.draw(face,imgx,imgy)
end
Scroll to Top