Search code examples
c++sdlpong

Drawing multiple instances of the same rect instead of moving it


class Pong {
public:
    Pong(int speed) {
        gSpeed = speed;

        gPongBG = SDL_LoadBMP("pongBG.bmp");

        gPongBGSurf = gPongBG;

        gPongRect.w = 800;
        gPongRect.h = 460;
        gPongRect.x = 700;
        gPongRect.y = 220;

        gPongPlayer = SDL_LoadBMP("pongPlayer.bmp");

        gPongPlayerRect.h = 50;
        gPongPlayerRect.w = 10;

        gPongPlayerRect.x = 50;
        gPongPlayerRect.y = 0;


    }

    ~Pong() {


    }

    void drawPong() {
        gPongBGSurf = gPongBG;
        SDL_BlitSurface(gPongBGSurf, NULL, gScreenSurface, &gPongRect);
        SDL_BlitSurface(gPongPlayer, NULL, gPongBGSurf, &gPongPlayerRect);
    }

    void movePlayer() {
        gPongPlayerRect.y++;
    }

The following code makes it so the gPongPlayerRect makes multiple copies of itself, rather than moving it as i planned. Later in the code, i update the main window named gWindow, and the surface of the main window is the wScreenSurface. If i blit the player directly onto the Window surface, it moves, so i guess the problem is that the old gPongBGSurf surface stays even tho its updated. How could i eventually fix this? Thanks!


Solution

  • My guess is that you forgot to erase the Pong Surface:

    Uint32 black= SDL_MapRGBA(gPongBGSurf->format,0,0,0,255);
    SDL_FillRect(gPongBGSurf, NULL, black);
    SDL_BlitSurface(gPongPlayer, NULL, gPongBGSurf, &gPongPlayerRect);
    SDL_BlitSurface(gPongBGSurf, NULL, gScreenSurface, &gPongRect);
    

    For a full example of a SDL2 game with multiple surfaces blitting on top of each other and then onto a screen surface, you can read the small source code of Rock Dodger CE which is only a single file.