Search code examples
luamouseeventmouselove2d

Waiting for user to lift mouse - not working: Love2D


I'm busy creating a program using the Love2D engine, where the user clicks and it returns the co-ordinates of the mouse's current location. Before returning another location, however, the user has to 'un-click' the mouse and then click at the next desired location.

I've pasted the script that should handle this below:

function scripts.waitForMouseLift()
    while love.mouse.isDown("l", "r") do
        --Stays in a loop until user releases mouse, then lets the program continue
    end
end

This should technically work, since the loop would end when the mouse click is lifted, but instead it just carries on in an infinite loop, regardless of which mouse button I clicked before.

So, my question consists of two parts: firstly, is there a way of making this method work? Secondly, are there any alternatives or better solutions to this problem?


Solution

  • Love uses callbacks for this and the one you're looking for is love.mousereleased and you might want to look at love.mousepressed too. These are functions you add to your script and whenever the user clicks (or releases) a mouse button the function is called. So you don't have to keep checking yourself to see if the mouse changed state and you can't wait for it in a busy loop since you need to give control back to Love so that it has a chance to update the mouse state.

    function love.mousepressed(x, y, button)
      -- do something with x, y
      print("Mouse Pressed", button, "at", x, y)
    end
    
    
    function love.mousereleased(x, y, button)
      print("Mouse Released", button, "at", x, y)
    end