Page 1 of 1
ouse clicked object
Posted: Sun Jun 01, 2014 6:29 pm
by BueDev
First off, i want to say sorry if there is already a thred on this (I know there is some where) but I've spent 30 minuets already looking for it. So here is my question, I want to simulate a command (if statement) when the mosue has clicked on a object. How would I do this?
Re: ouse clicked object
Posted: Sun Jun 01, 2014 9:38 pm
by Germanunkol
You probably didn't find anything in your search because there is so many ways to do this...
The basic, simplest way I can currently think of is this:
In
love.mousepressed, check if the mouse was inside the region which is also the region where the object currently is.
If so, call the function.
Here's a quick example. This should make the rectangle change color every time it's clicked (not tested)
Code: Select all
local object = { x = 10, y = 20, width = 100, height = 50, color = 0 }
function love.mousepressed( x, y, button )
-- Check if the click is inside the object:
if x > object.x and y > object.y and x < object.x + object.width and y < object.y + object.height then
switchObjectColor()
end
end
function switchObjectColor()
if object.color == 0 then
object.color = 1
else
object.color = 0
end
end
function love.draw()
if object.color = 0 then
love.graphics.setColor( 255, 0, 0, 255 )
else
love.graphics.setColor( 0, 255, 0, 255 )
end
love.graphics.rectangle( "fill", object.x, object.y, object.width, object.height)
end
Edit:
P.S. Welcome to the forums!
Re: ouse clicked object
Posted: Sun Jun 01, 2014 9:40 pm
by Chron
Basically, you treat it similarly to how you would treat collisions in gameplay.
Assuming the object you want to check for collision with the mouse is a rectangle, for example a button, here's a function you could use to check for collision between a point (the mouse position) and a rectangle (the button):
Code: Select all
function pointRectangleCollide(pointX, pointY, rectangleX, rectangleY, rectangleWidth, rectangleHeight)
left = rectangleX
right = left + rectangleWidth
top = rectangleY
bottom = top + rectangleHeight
return
left <= pointX and
top <= pointY and
pointX <= right and
pointY <= bottom
end
What this function does is check if the point is
- - To the right of the left line of the rectangle,
- Below the top line of the rectangle,
- To the left of the right line of the rectangle,
- And above the bottom line of the rectangle.
If all is true, then the point is inside the rectangle, and therefore colliding. Only in this case, the function above returns true.
Other shapes, such as rotated rectangles, are more complicated - I suggest you to read up 2D collisions on the internet if you want to learn more.
Re: ouse clicked object
Posted: Sun Jun 01, 2014 11:33 pm
by BueDev
thank you so much for your responses! also, I am very sorry about the errors in the post, I was typing quickly, and shortly found out that my keyboard became unresponsive
still, no excuse for ill grammar. Thank you for your warm welcome to!