0

I'm new to LUA and I'm making a simple game where a bunny should bounce after pressing space on the keyboard. So the plan is to make the bunny go up by 30, wait for half a second and then for the bunny to go back to its original position.

That's the code that I've tried so far, and for the looks of it, the love.keypressed function completely ignored the wait function and tried to execute everything at the same time, which means the bunny simply does not move if the spacebar is pressed. (In other words, is there a way to make the bunny stay in the air for 0.5 seconds after pressing the spacebar and then making it go back to its original position?)

function wait(millisecond)
end

function love.keypressed(key)
    if key == "space" then
        bunny.y = bunny.y - 30
        wait(500);
        bunny.y = bunny.y + 30
    end
end

  • This is a very broad questions with a set of possible ways to implement this. You can give your bunny a jump timer, you can work with a timer and callbacks, if you want to use sleep you may use coroutines and one coroutines per entity. Really depends on the project and what you like the most. – Luke100000 Dec 26 '22 at 21:11
  • This presumably won't work as it just blocks the Lua thread and thus `love.draw` doesn't even get called after it has run. Instead, you *must* work with a timer. – Luatic Dec 27 '22 at 10:29

2 Answers2

1

For love2d this should work -> https://love2d.org/wiki/love.timer.sleep

An a pure lua sleep function would look like this:
(the time is in seconds)

local function sleep(time)
    local start = os.clock()
    while os.clock() - start <= time do end
end
0

The best way to do this without blocking the Lua thread (which would cause ALL functions to stop, including graphics and parsing data) is to create a timer. This library does exactly what you're looking for.

In the end, your function would look like this (assuming you've imported the library correctly):

function love.keypressed(key)
    if key == "space" then
        bunny.y = bunny.y - 30
        timer.Simple(0.5, function() -- wait 0.5 seconds, and then run the code
            bunny.y = bunny.y + 30
        end)
    end
end
dave
  • 1
  • 2