SDL 按钮/事件停止工作

SDL button / event stops working

本文关键字:停止工作 事件 按钮 SDL      更新时间:2023-10-16

在创建一个简单的游戏时,我一直在按照lazyfoo' Productions的教程一步一步地学习。我目前的任务是制作主菜单,这就是我的问题所在。

我对全局变量充满热情,因此我不使用它们;我相信它们太难准确跟踪和维护了,但这不是重点。本教程使用屏幕的全局变量以及其他一些内容。我已经设法计算出一个按钮类,但它在拒绝更改精灵之前只能工作一定的时间(大约 7 秒)。

我仍然可以正常退出,但按钮的纹理将与停止时相同(如果鼠标悬停在它上面,它将保持发光,反之亦然)。

这是我的主线程,我在其中调用按钮的类函数:

//...
while(quit == false)
{
    if(SDL_PollEvent(&event))
    {
        if(event.type == SDL_QUIT)
        {
            quit = true;
        }
        else if(event.type == SDL_MOUSEMOTION)
        {
            button_newgame.handle_events(event);
        }
    }
    button_newgame.show();
    if(SDL_Flip(screen) == -1)
    {
        return 0;
    }
}

这是按钮功能

Button::Button(int x, int y, int w, int h, int buttonnum, SDL_Surface *screen)
{
box.x = x;
box.y = y;
box.w = w;
box.h = h;
m_screen = screen;
switch(buttonnum)
{
case 0:
    buttonclipinactive.x = 0;
    buttonclipinactive.y = 0;
    buttonclipinactive.w = 240;
    buttonclipinactive.h = 60;
    buttonclipactive.x = 0;
    //setting clips according to the button's identiffying number to find the correct sprite
}
void Button::handle_events(SDL_Event event)
{
//The mouse offsets
int mx = 0, my = 0;
SDL_Delay(5);
//Get the mouse offsets
mx = event.motion.x;
my = event.motion.y;
//If the mouse is over the button
if( ( mx > box.x ) && ( mx < box.x + box.w ) && ( my > box.y ) && ( my < box.y + box.h ) )
{
    //Set the button sprite
    clip = &buttonclipactive;
}
//If not
else
{
    //Set the button sprite
    clip = &buttonclipinactive;
}
SDL_Rect* Button::show()
{
    SDL_Surface *mainmenuoptionsheet = load_image("images/mainmenuoptionsheet.bmp");
    apply_surface(box.x, box.y, mainmenuoptionsheet, m_screen, clip);
}

你称Button::show()在你的循环中打勾。但是这个功能到底有什么作用呢?

SDL_Surface *mainmenuoptionsheet = load_image("images/mainmenuoptionsheet.bmp");

因此,您每次都会加载 bmp。您的程序停止显示可能是因为它(可预见地)耗尽了要使用的内存,并且卡在显示的最后一个子画面上。因此,相反,在应用程序开始时加载一次SDL_Surface指针,然后呈现每一帧。

作为附加说明,请确保您使用的是最新的 lazyfoo 教程。他的旧过时了。