how to check if mouse is over an object?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
badfitz66
Prole
Posts: 29
Joined: Sat Jun 07, 2014 10:30 pm

how to check if mouse is over an object?

Post by badfitz66 »

I want to be able to grab a object in my scene, how can I check if the mouse is over a object's body?
What a wonderful caricature of intimacy
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: how to check if mouse is over an object?

Post by Plu »

You'll have to calculate it, so it depends a lot on what the object looks like. For circular objects, you can use a simple distance calculation between the mouse's location and the center of the circle using it's radius. For rectangular objects, you can use a bounding-box check (if you google that term you should plenty of info).

If it's a more complex shape, it'll be a little harder to determine so it'd probably be best to use some sort of library for it.
lumlune
Prole
Posts: 12
Joined: Fri May 02, 2014 9:50 pm

Re: how to check if mouse is over an object?

Post by lumlune »

Plu wrote:If it's a more complex shape, it'll be a little harder to determine so it'd probably be best to use some sort of library for it.
If it's an image with its negative space transparent, you can look at the pixel the cursor is over and check the alpha value.

Something like...

Code: Select all

mouse_x, mouse_y = love.mouse.getPosition()

-- area = image boundaries
function cursorIsOver(area)
    local x = mouse_x - area.topLeft.x
    local y = mouse_y - area.topLeft.y

    if (x < area.width and y < area.height) then
        local r, g, b, a = [[ ImageData object ]]:getPixel(x, y)

        if a ~= 0 then
            return true
        end
    end

    return false
end
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 3 guests