0

マウスが最初の最初のボタンの上にあるときにスクリプトが2番目のボタンをロードするようにする簡単なスクリプトがあります。しかし、それはtrueに戻らないので、私はそれを機能させることができないようです。

これは状況をチェックする私のクラスです:

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を返すように見えません。なぜこれが起こるのか、何か考えはありますか?

4

1 に答える 1

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.
}
于 2012-11-04T00:13:04.753 に答える