Search code examples
for-looplualove2d

Love2d cursor positions


I have a question about the love2d(lua script) cursor functions. I wan't to make an area to click to make an action happen.

I started on a track of for loops in the x and y parameters. The only other problem ive thought of is if it will go through a for loop of number/coordinates and finish on 1 number which the love.mouse.get() will end up on and allow for the cursor to end up being clicked on that last coordinate(one pixel).

for r = 660, 770 do --the x coordinates
mx = love.mouse.getX(r)
end

for f = 99.33, 169.66 do  --the y coordinates
my = love.mouse.getY(f)
end

And how would I combine the two for loop variables(r and f).

To sum everything up I want to be able to click on an area and do an action. I know there are no love.load, love.update, and love.draw functions because this is just a test file to learn how all this works.

Thank you :)


Solution

  • You're overthinking this problem. What you really want to do is define a minimum and a maximum in two dimensions, listen for mouse events, and then check if the mouse location is within your boundaries. There is no need to loop over your entire ranges.

    Consider this example 'game' where we draw a simple red box which when clicked toggles the display of text in the top left corner.

    local box_dims = {
        { 660, 770 },
        { 99.33, 169.66 }
    }
    
    local show = false
    
    function love.mousepressed (x, y)
        if
            x >= box_dims[1][1] and
            x <= box_dims[1][2] and
            y >= box_dims[2][1] and
            y <= box_dims[2][2] then
    
            show = not show
        end
    end
    
    function love.draw ()
        love.graphics.setColor(255, 0, 0, 255)
    
        love.graphics.rectangle('fill',
            box_dims[1][1], box_dims[2][1],
            box_dims[1][2] - box_dims[1][1],
            box_dims[2][2] - box_dims[2][1]
        )
    
        if show then
            love.graphics.print('hello world', 10, 10)
        end
    end
    

    Take a look at the documentation to decide which mouse event is right for you.