SFML community forums
Help => Graphics => Topic started by: langisser on January 08, 2010, 08:04:18 am
-
how to detect when mouseover/click an object
Example:
I want to create my event when mouseover/click a string or image. How to?
-
Get the surrounding rectangle of your object and check, whether it contains the mouse coordinate (delivered by a MouseButtonPressed event).
sf::String (sf::Text in SFML2) has a method GetRect(), at sf::Sprite you have to calculate the bounding rect with position, size and origin.
-
That's cool.
This's my code.
int MouseOver(int MouseX,int MouseY,sf::String Hello)
{
//return 0 = mouse over
//retunr 1 = mouse not over
if ( MouseX > Hello.GetRect().Left && MouseX < Hello.GetRect().Right)
{
if ( MouseY > Hello.GetRect().Top && MouseY < Hello.GetRect().Bottom)
return 0;
}
return 1;
}
-
Why don't you use bool? :shock:
And why are there two ifs? One is enough.
Besides, I would pass Hello by const reference and store the rectangle given by Hello.GetRect() (you can't be sure SFML doesn't calculate it every time, and even if, this is an implementation detail and might change in the future).
P.S. I found a mistake in my upper post, of course I meant sf::Sprite and not sf::String a second time.
-
Thank you for recommend,Now i use bool.
-
You can use the Contains method of the rect.
bool Match (float x, float y)
{
// m_rect is of type sf::FloatRect
return m_rect.Contains (x,y);
}