Sudden Black Screen Issue After Adding Gravity to C++ SDL Game

I’m making a game in C++ that uses a library called SDL and there is an issue where when the player presses play and goes to the second scene where the bed, floor and background are there but Arthur is not, and then after a split second everything disappears and it just goes black. The project is in three coding files and they will be separate pastebin documents. This problem started after I added gravity.

1: // Snooping through the files are we?// Compile With: g++ main.cpp loadImage - Pastebin.com
2: // Snooping through the files now are we?// Compile With: g++ main.cpp loadI - Pastebin.com
3: // Snooping through the files now are we?// Compile With: g++ main.cpp loadI - Pastebin.com

I think I have heard of that one… :wink:

I think the following code is to blame for the black screen.

int imageIndexHolder;
imageIndexHolder = loadImage(arthur, playerX, playerY, 118, 174);
imageIndexHolder--;
freeImageSlot(imageIndexHolder);

Arthur is not shown because you remove his image slot before showing it.

Since you keep calling this each time, loadImage will soon restart imageIndex from 1 and start overwriting the other image slots which is why everything becomes black.


The image slot code has a lot of code repetition. You might want to consider using arrays (or a resizable container such as std::vector) and loops to get rid of that. Same for the hit boxes.

2 Likes

I just do this because I don’t know how to call a variable by a name made up of a string or any other way to do something like that. Also you explaining this made me fix it thank you!

What I mean is that instead of having 10 variables

SDL_Texture* imageSlot1;
SDL_Texture* imageSlot2;
SDL_Texture* imageSlot3;
...
SDL_Texture* imageSlot10;

you could have an array with 10 elements

SDL_Texture* imageSlot[10];

and instead of repeating the code 10 times whenever you want to do something with them you just have to write it once.

For example, if you let imageIndex go from 0 to 9 instead of 1 to 10 you can use it as an array index inside loadImage so the switch could be replaced by something like:

imageRect[imageIndex].x = posX;
imageRect[imageIndex].y = posY;
imageRect[imageIndex].w = sizeX;
imageRect[imageIndex].h = sizeY;
imageSlot[imageIndex] = IMG_LoadTexture(renderer, path);
std::cout << "imageIndex " << imageIndex << " loaded." << std::endl;
imageIndex++;

And in renderScreen you could use a for loop:

for (int i = 0; i < 10; ++i)
{
	SDL_RenderCopy(renderer, imageSlot[i], NULL, &imageRect[i]);
}

There might be better ways to do these things but at least this removes a lot of the code repetition.

Nice, I might implement that later.