鼠标悬停在SDL / C ++中无法正常工作

时间:2012-11-03 23:57:39

标签: c++ sdl

我有一个简单的脚本,当鼠标悬停在第一个初始按钮上时,我希望脚本加载第二个按钮。但它不会返回真实,所以我似乎无法让它发挥作用。

这是我的班级检查情况:

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 );

    }
};

我试图开始工作的IsIn函数......在我的主循环中我有:

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工作正常,但是当我将鼠标悬停在btn_quit按钮上时,我似乎无法在case语句之后获得if语句返回true。任何想法为什么会这样?

1 个答案:

答案 0 :(得分:1)

因为btn_quit没有宽度或高度,所以你永远不能进入它的界限。

Button btn_quit(screen->w/2,screen->h/2,0,0);

您的检查会失败,因为您的鼠标位置永远不会是>x && <x+0>y && <y+0

或许更好的方法是定义按钮的位置,然后从加载的图像中获取尺寸?

class Button
{
  public:
    // Construct the button with an image name, and position on screen.
    // This is important, your existing code loaded the image each render.
    // That is not necessary, load it once when you construct the class.
    Button(std::string name, int x, int y) : img(IMG_Load(name)) 
    {
      if(img) // If the image didn't load, NULL is returned.
      {
        // Set the dimensions using the image width and height.
        offset.x = x; offset.y = y;
        offset.w = img.w; offset.h = img.h;
      }
      else { throw; } // Handle the fact that the image didn't load somehow.
    }     
    ~Button() { SDL_FreeSurface(img); } // Make sure you free your resources!
    void Render(SDL_Surface *destination)
    {
      // Simplified render call.
      SDL_BlitSurface(img, NULL, destination, &offset );
    }
    bool Contains(int x, int y)
    {
      if((x>offset.x) && (x<offset.x+offset.w)
      && (y>offset.y) && (y<offset.y+offset.h))
      return true; // If your button contains this point.
      return false;  // Otherwise false.
    }
  private:
    SDL_Rect offset; // Dimensions of the button.
    SDL_Surface* img; // The button image.
}
相关问题