跳过代码片段 C++ SDL2

Skip fragment of code C++ SDL2

我正在使用 SDL2 库用 C++ 编写一个函数,但遇到了一个小问题。该函数处理与图形相关的一切。我想用它一次来创建 window、表面等等 ( graphics(0,0) ),之后每次我使用它时它都会更新xy 的值,并更新 window 表面。我该怎么做?我已经尝试了所有我能想到的方法,但为了更新 window 表面,我需要再次创建 window。提前致谢。

void graficos(int var1,int var2){
    int x = 0, y = 0; //declare the variables that will determine position of rectangle
    x += var1; y += var2; //declare the variables that will modify x & y
    //delcare graphics and load them
    SDL_Window * window = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Surface * surface = SDL_GetWindowSurface(window);
    SDL_Surface * texture = SDL_LoadBMP("texture.bmp");
    SDL_Rect rectangle = { x, y, 50, 50 };
    //render graphics
    SDL_BlitSurface(texture, NULL, surface, &rectangle);
    //update window
    SDL_UpdateWindowSurface(window);
    }

第一。您可以将您的函数分成两部分:initgraficos,如下所示:

void init( SDL_Window * &window, SDL_Surface * &texture ) {
    window = SDL_CreateWindow("window",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        640,
        480,
        0
    );
    texture = SDL_LoadBMP("texture.bmp");
}

void graficos( SDL_Window * window, SDL_Surface * texture, int var1, int var2 ) {
// You can delete these lines and use var1 and var2 directly
    /*    int x = 0, y = 0; //declare the variables that will determine position of rectangle
    x += var1; y += var2; //declare the variables that will modify x & y
    */
    SDL_Surface * surface = SDL_GetWindowSurface(window);
    SDL_Rect rectangle = { var1, var2, 50, 50 };
    //render graphics
    SDL_BlitSurface(texture, NULL, surface, &rectangle);
    //update window
    SDL_UpdateWindowSurface(window);
}

这是用法:

// somewhere in global place
SDL_Window * window;
SDL_Surface * texture;

// somewhere in initialization of programm
init( window, texture ); // call it only ones
...

graficos( window, texture, newX, newY ); // call it every time you need

第二。您可以像这样将 windowtexture 设为 static

void graficos(int var1,int var2){
    /*        int x = 0, y = 0; //declare the variables that will determine position of rectangle
    x += var1; y += var2; //declare the variables that will modify x & y
    */
    //delcare graphics and load them
// ---v---
    static SDL_Window * window = SDL_CreateWindow("window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
// ---^---
    SDL_Surface * surface = SDL_GetWindowSurface(window);
// ---v---
    static SDL_Surface * texture = SDL_LoadBMP("texture.bmp");
// ---^---
    SDL_Rect rectangle = { x, y, 50, 50 };
    //render graphics
    SDL_BlitSurface(texture, NULL, surface, &rectangle);
    //update window
    SDL_UpdateWindowSurface(window);
}

如果要投票,那么我的声音将是第一个 :)