I have a simple script where by i want the script to load a second button when the mouse is hovering over the first initial button. But it won’t return true so i can’t seem to get it to work.
This is my class which checks the situation:
class Button
{
private:
int m_x, m_y;
int m_width, m_height;
public:
Button(int x, int y, int width, int height)
{
m_x = x;
m_y = y;
m_width = width;
m_height = height;
}
bool IsIn( int mouseX, int mouseY )
{
if (((mouseX > m_x) && (mouseX < m_x + m_width))
&& ((mouseY > m_y) && (mouseY < m_y + m_height ) ) ) {
return true;
} else {
return false;
}
}
void Render(SDL_Surface *source,SDL_Surface *destination)
{
SDL_Rect offset;
offset.x = m_x;
offset.y = m_y;
offset.w = m_width;
offset.h = m_height;
source = IMG_Load("button.png");
SDL_BlitSurface( source, NULL, destination, &offset );
}
};
Its the IsIn function I am trying to get to work… in my main loop i have:
while(!quit){
while( SDL_PollEvent( &event ) )
switch( event.type ){
case SDL_QUIT: quit = true; break;
case SDL_MOUSEMOTION: mouseX = event.motion.x; mouseY = event.motion.y; break;
}
Button btn_quit(screen->w/2,screen->h/2,0,0);
btn_quit.Render(menu,screen);
if(btn_quit.IsIn(mouseX,mouseY)){
Button btn_settings(screen->w/2,screen->h/2+70,0,0);
btn_settings.Render(menu,screen);
}
SDL_Quit works fine but i can’t seem to get the if statement after the case statement to return true when i hover the mouse over the btn_quit button. Any ideas why this might be ?
Because
btn_quithas no width or height, and therefore you can never be inside it’s bounds.You checks will fail because your mouse position can never be
>x && <x+0or>y && <y+0.Perhaps a better way would be to define the location of your button, and let get the dimensions from the loaded image?