While循环会导致SDL_Rect和SDL_Textures滞后吗?

时间:2018-12-11 15:15:02

标签: c++ rendering sdl lag rect

我正在使用C ++和SDL制作游戏,该游戏是“太空侵略者”类型的游戏。一切都进行得很顺利,直到我在while循环中添加了背景图片,这是背景的渲染和初始化代码:

SZ_Background.cpp:

void SZ_Background::Init(SDL_Renderer* pRenderer)
{
    int w, h;

    SDL_GetRendererOutputSize(pRenderer, &w, &h);

    bg_img.x = 0;
    bg_img.y = 0;
    bg_img.h = h;
    bg_img.w = w;

    SDL_Surface* background_img = IMG_Load("content/bg_img.bmp");
    SDL_Texture* background_img_tex = SDL_CreateTextureFromSurface(pRenderer, background_img);

    SDL_RenderCopy(pRenderer, background_img_tex, NULL, &bg_img);
}

void SZ_Background::Render(SDL_Renderer* pRenderer)
{
    int w, h;

    SDL_GetRendererOutputSize(pRenderer, &w, &h);

    bg_img.x = 0;
    bg_img.y = 0;
    bg_img.h = h;
    bg_img.w = w;

    SDL_Surface* background_img = IMG_Load("content/bg_img.bmp");
    SDL_Texture* background_img_tex = SDL_CreateTextureFromSurface(pRenderer, background_img);

    SDL_RenderCopy(pRenderer, background_img_tex, NULL, &bg_img);
}

main.cpp-循环:

if (GameState == 3)
    {
        printf("INFO: Game State: %d - Game Screen Loaded\n", GameState);
        mainEnemies.gameover = false;
        mainBG.Init(game_renderer);
        gOver.Init(game_renderer);
        while (!done)
        {
            aTimer.resetTicksTimer();

            SDL_SetRenderDrawColor(game_renderer, 0, 0, 20, SDL_ALPHA_OPAQUE);
            SDL_RenderClear(game_renderer);

            mainBG.Render(game_renderer);

            gOver.Update(game_renderer);
            gOver.Input();
            gOver.Render(game_renderer);

            SDL_RenderPresent(game_renderer);

            if (gOver.rMenu == true)
            {
                SDL_RenderClear(game_renderer);
                SDL_RenderPresent(game_renderer);
                GameState = 0;
                break;
            }

            if (aTimer.getTicks() < DELTA_TIME)
            {
                SDL_Delay(DELTA_TIME - aTimer.getTicks());
            }
        }
    }

mainBG是背景。

1 个答案:

答案 0 :(得分:1)

问题在于,每次调用background_img时,您都要初始化background_img_texSZ_Background::Render

SDL_Surface* background_img = IMG_Load("content/bg_img.bmp");
SDL_Texture* background_img_tex = SDL_CreateTextureFromSurface(pRenderer,background_img);

这不是必需的,您已经在SZ_Background::Init中对其进行了初始化,这就是您需要做的。现在的方式不仅会通过每帧从磁盘加载背景来减慢程序速度,而且每次还会泄漏内存(主要是SDL_Surface的RAM,以及SDL_Texture的GPU内存)。删除IMG_Load中的SDL_CreateTextureFromSurfaceRender调用,这样会更好。