Page 1 of 1

how to check if mouse is over an object?

Posted: Thu Aug 28, 2014 5:43 am
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?

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

Posted: Thu Aug 28, 2014 6:23 am
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.

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

Posted: Thu Aug 28, 2014 1:05 pm
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