2013-05-02 79 views
0

我和我的朋友需要创建一个反应时间游戏。 东西like thisC++ SDL反应时间游戏

现在我们只是设法显示一个红色按钮的图像,但我们需要帮助如何使一个hitbox,如果你点击红色按钮,它会变成绿色。

有人可以告诉我们如何?

我们正在使用SDL,我想这很重要。

这是到目前为止我们的代码:

#include <SDL/SDL.h> 

void Plot(SDL_Surface *sur, int x, int y, SDL_Surface *dest) 
{ 
    SDL_Rect rect = {x, y}; 
    SDL_BlitSurface(sur, NULL, dest, &rect); 
} 

SDL_Surface *LoadImage(const char *filename) 
{ 
    SDL_Surface *sur = NULL; 
    sur = SDL_LoadBMP(filename); 

    if(sur == NULL) 
    { 
     printf("Img not found"); 
    } 

    SDL_Surface *opsur = NULL; 

    if(sur != NULL) 
    { 
     opsur = SDL_DisplayFormat(sur); 
     SDL_SetColorKey(opsur, SDL_SRCCOLORKEY, 0xFFFFFF); 
     if(opsur != NULL) 
      SDL_FreeSurface(sur); 
    } 

    return opsur; 
} 

int main(int argc, char **argv) 
{ 
    SDL_Init(SDL_INIT_EVERYTHING); 
    SDL_Surface *screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE); 
    SDL_WM_SetCaption("Eksamensprojekt", NULL); 
    SDL_Event Event; 
    bool Running = true; 

    SDL_Surface *sur = LoadImage("Red.bmp"); 

    while(Running) 
    { 
     while(SDL_PollEvent(&Event)) 
     { 
      if(Event.type == SDL_QUIT) 
       Running = false; 
     } 
     SDL_FillRect(screen, &screen->clip_rect, 0x000000); 

     Plot(sur, 215, 140, screen); 

     SDL_Flip(screen); 
    } 

} 

回答

0

您可以使用SDL_Rect作为命中框。您可以使用SDL自己的事件处理系统来检查何时点击鼠标按钮及其位置。然后您只需检查鼠标位置是否在SDL_Rect内。

你可以阅读更多关于SDL here. 所以...在路上的一点帮助。你有一个主循环,你拉事件。

if (event.type == SDL_MOUSEBUTTONDOWN){ 

    //Get mouse coordinates 
    int x = event.motion.x; 
    int y = event.motion.y; 

    //If the mouse is over the button 
    if(checkSpriteCollision(x, y)){ 
     // Yay, you hit the button 
     doThings(); 
    } 
    else 
    { 
     // D'oh I missed 
    } 

} 

一下添加到时,将至少让你开始。

+0

我们已经看着它,并企图,仍然未能:(如果您或任何其他人可以写出来对我们来说将是真正伟大:) – user2298880 2013-05-02 14:08:30

+0

感谢您的回答,但我们仍然不能让它工作。有2个函数,我可以将它插入到哪个函数中?我怎么让它点击时显示绿色按钮?我希望它在点击时从红色变为绿色。 – user2298880 2013-05-02 14:49:25

+0

把它放在内部循环中(在if(event.type == SDL_Quit)')下 要切换颜色,你应该基本上和在plot函数中做的一样,只用绿色表面而不用红色。你可以使用布尔值来确定你应该blit的两个表面中的哪一个。 – olevegard 2013-05-02 14:55:00

0

是否这样?

while(Running) 
    { 
     while(SDL_PollEvent(&Event)) 
     { 
      if(Event.type == SDL_QUIT) 
       Running = false; 

      if (event.type == SDL_MOUSEBUTTONDOWN){ 

       //Get mouse coordinates 
       int x = event.motion.x; 
       int y = event.motion.y; 

       //If the mouse is over the button 
       if(checkSpriteCollision(x, y)){ 
        // Yay, you hit the button 
        doThings(); 
       } 
       else { 
        // D'oh I missed 
       } 

      } 
     } 
     SDL_FillRect(screen, &screen->clip_rect, 0x000000); 

     Plot(sur, 215, 140, screen); 

     SDL_Flip(screen); 
    } 

} 
+0

请有人编程帮助我们:D – user2298880 2013-05-02 15:15:19

+0

是的,现在你有代码检查是否有人点击按钮(假设你实验'CheckSpriteCollision(x,y)'功能 但你需要移动'Plot ...)“,这样当有人点击按钮时,绿色表面会闪烁,反之则红色按钮。 – olevegard 2013-05-02 15:48:41