Page 1 of 1
checking if a mouse is over a rectangle
Posted: Fri Aug 22, 2014 2:45 pm
by silverknight108
hello all again
i have a problem i have a grid and i want to check exactly what square the mouse clicks and change its color
here is my grid code
Code: Select all
function dg()
h,w = love.window.getHeight,love.window.getWidth
bloks = {}
for x = 0,12 do
bloks[x] = {}
for y = 0,12 do
bloks[x][y] = {}
bloks[x][y] = love.graphics.rectangle("line",x*45,y*45,45,45)
end
[code/]
end
end
]
Re: checking if a mouse is over a rectangle
Posted: Fri Aug 22, 2014 3:53 pm
by Zulsorai
The first thing I would do off the top off my head would to use a simple aabb collision function. If you know the x and y position of the box and have it at a set width and height then you can do something like:
Code: Select all
if mx >= x and mx <= x + width then
if my >= y and my < y + height then
-- Do whatever here
end
end
The
mx and
my of course being the mouse position and the
x,
y,
width, and
height all coming from what you want to check it againts. Hopefully thats enough to help you figure everything out.
Cheers
Re: checking if a mouse is over a rectangle
Posted: Fri Aug 22, 2014 3:58 pm
by silverknight108
Re: checking if a mouse is over a rectangle
Posted: Fri Aug 22, 2014 4:08 pm
by Zulsorai
Looking at the code you posted you get the x and y position saved as block[x][y] multiplied by 45 (The same way you are drawing it)
Without a .love thats really all I can do. Hopefully this makes sense.
Re: checking if a mouse is over a rectangle
Posted: Sun Aug 31, 2014 8:02 pm
by Luke100000
Code: Select all
function dg()
h,w = love.window.getHeight,love.window.getWidth
bloks = {}
for x = 0,12 do
bloks[x] = {}
for y = 0,12 do
bloks[x][y] = {}
bloks[x][y] = love.graphics.rectangle("line",x*45,y*45,45,45)
end
[code/]
end
end
function love.mousepressed(x, y, button)
local blokSize = 45 --like the rectangle in dg()
local blokX, blokY = math.floor(x/blokSize), math.floor(y/blokSize)
--now you have the position of the selected block
if button == "l" then --left mousebutton
--change color
end
end
You don't need to check every "blok" if it is selected, because only one at time can be the one.
I hope I understood you question and helped you...