2012-11-03 81 views
0

我有一個簡單的腳本,當我想讓腳本在鼠標懸停在第一個初始按鈕上時加載第二個按鈕。但它不會返回真實,所以我似乎無法得到它的工作。SDL/C++中的鼠標懸停不起作用

這是我的類檢查情況:

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作品好,但我似乎無法得到if語句後case語句返回true時,我將鼠標懸停在btn_quit按鈕上。任何想法,爲什麼這可能是?

回答

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. 
} 
+0

我以爲它定義了它的寬度和高度,因爲我添加了可以設置它的圖像? – Sir

+0

我沒有看到該代碼中的圖像會操縱Button類的成員。你需要明確地設置它,或者找到一種方法來獲得'IMG_load'對象的尺寸。 – Aesthete

+0

好吧我必須誤解,因爲我認爲當你blit一個圖像,將設置新的尺寸從0和0到圖像寬度和高度=/ – Sir