SDL and c++ -- More efficient way of leaving a trail behind the player?

so i'm fairly new with SDL, and i'm trying to make a little snowboarding game. When the player is moving down the hill, I want to leave a trail of off-coloured snow behind him. Currently, the way i have this working is I have an array (with 1000 elements) that stores the players last position. Then each frame, I have a for loop that loops 1000 times, to draw out the trail texture in all these last 1000 positions of the player...

I feel this is extremely inefficient, and i'm looking for some better alternatives!

The Code:

void Player::draw()
    if (posIndex >= 1000)
        posIndex = 0;

    for (int i = 0; i < 1000; i++) // Loop through all the 1000 past positions of the player
        // pastPlayerPos is an array of SDL_Rects that stores the players last 1000 positions
        // This line calculates teh location to draw the trail texture
        SDL_Rect trailRect = {pastPlayerPos[i].x, pastPlayerPos[i].y, 32, 8};
        // This draws the trail texture
        SDL_RenderCopy(Renderer, Images[IMAGE_TRAIL], NULL, &trailRect);

    // This draws the player
    SDL_Rect drawRect = {(int)x, (int)y, 32, 32};
    SDL_RenderCopy(Renderer, Images[0], NULL, &drawRect);

    // This is storing the past position
    SDL_Rect tempRect = {x, y, 0, 0};
    pastPlayerPos[posIndex] = tempRect;

    posIndex++; // This is to cycle through the array to store the new position

The result

This is the result, which is exactly what i'm trying to accomplish, but i'm just looking for a more efficient way. If there isn't one, i will stick with this.


  • There are multiple solutions. I'll give you two.


    Create screen-size surface. Fill it with alpha. On each player move, draw it's current position into this surface - so each movement will add you extra data to this would-be mask. Then blit this surface on screen (beware of blit order). In your case it could be improved by disabling alpha and initially filling surface with white, and blitting it first, before anything else. With that approach you can skip screen clearing after flip, by the way.

    I recommend starting with this one.


    Not easy one, but may be more efficient (it depends). Save array points where player actually changed movement direction. After it, you need to draw chainline between these points. There is however no builtin functions in SDL to draw lines; maybe there are in SDL_gfx, i never tried it. This approach may be better if you'll use OpenGL backend later on; with SDL (or any other ordinary 2D drawing library), it's not too useful.