I'm trying to fade textures onto the screen using SDL2.

I've tried some different methods I've looked up, but I always encounter the same problem. It seems that the fading takes longer and longer as Alpha gets higher and higher, meaning that the very end of the fade takes the longest amount of time, and thus the fade takes an unreasonably long amount of time. I want the image to fade in at the same rate, and not dramatically slow down when the image gets more and more opaque.

The code that was causing the issue described above has been deleted, and I'm working on an entirely new system to hopefully avoid the problem. However, it doesn't work at all. Any advice would be awesome!

My NEW code:

for (float alpha = 0; alpha <= SDL_ALPHA_OPAQUE; alpha += fadeSpeed * elapsedTime) {
        if (SDL_SetTextureAlphaMod(spriteTex, alpha) == -1) cout << "ERROR" << endl;
        SDL_RenderCopy(renderer, spriteTex, NULL, &destRect);
        cout << "ALPHA: " << alpha << endl;
  • \$\begingroup\$ What does "it doesn't work at all" mean? It doesn't fade in? If not, what does it do? Also, the original problem is hard to understand from your description. Was it taking longer to render each frame as it got towards the end (did the fps slow down?), or was it just that the amount of opacity didn't seem to change at a constant rate? \$\endgroup\$ Jan 3 '18 at 5:17
  • 3
    \$\begingroup\$ You do this in a for loop. The game probably doesn't have time to show each phase of the fade, because it all happens in a single frame. \$\endgroup\$
    – Bálint
    Jan 3 '18 at 8:51
  • \$\begingroup\$ @user1118321 As the opacity increased, the rate at which the opacity increased APPEARED to become slower and slower. The problem with the current code is that the image doesn't fade in at all. It is invisible for the duration of the fade. At the end of the fade, it appears at full opacity. \$\endgroup\$ Jan 4 '18 at 0:02
  • \$\begingroup\$ @Bálint So can I add an SDL_Delay in the for loop to correct the problem? \$\endgroup\$ Jan 4 '18 at 0:04
  • \$\begingroup\$ Do you have a game loop where you render to the screen? \$\endgroup\$
    – Jay
    Jan 4 '18 at 4:45

@Jay was absolutely right. I am going to make a separate fade function, which takes a background and image parameter.

This function will:

1) Draw background

2) Draw sprite with alpha starting at zero

3) Increase alpha

4) Loop until alpha reaches SDL_ALPHA_OPAQUE (255)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.