Search code examples
c++staticalphadecrement

Decrement float from 1.0f to 0.0f (C++)


I'm trying to set a screen alpha amount from 1.0f to 0.0f (complete fade out). I have the following defined:

static float cur_alpha;

And the function to do it is named HUD_FadeAlpha. There is also a HUD_SetAlpha, but it only contains {cur_alpha = alpha;}, where FadeAlpha attempts to set alpha and decrement the float to 0.0f:

void HUD_FadeAlpha(float alpha)
{
    cur_alpha = alpha;
    int i;

    for (int i = 0; i < 100; i-- )
    {
      alpha = 1.000f + i/1.000f;
    }

}

This is supposed to decrement the alpha value from 1.0f to 0.0f (transparent). It is only to be used with this:

void Message_Drawer(void)
{
    CON_ShowFPS();

    if (message_on)
    {
        HUD_SetAlpha(1.000f); // sets the alpha
        HUD_SetAlignment(0, 0);
        HUD_DrawText(160- 3 / 2, 3, w_message.c_str());
        HUD_FadeAlpha();//******** the function to fade out. ********
        HUD_SetScale();
        HUD_SetAlignment();
        HUD_SetAlpha();
        HUD_FadeAlpha();
    }

}

But for some reason, it isn't working, it's acting like there isn't anything to decrement, so it just draws the text to screen and disappears without an alpha fading effect. . . (?)

What I'm trying to do is have the message start at 1.0f, and fade out to 0.0f, since HUD_Alpha sets it to solid, and needs to fade to nothing after the message has been drawn to the screen . For some reason, it's not working correctly, so maybe I'm not setting it up right. Not sure if this needs to be done in HUD_FadeAlpha or in Message_Drawer.

So basically, from 1.0f -> 0.75f, 0.5f, 0.25f, 0.0f, but decremented quickly and smoothly, using 3 decimal places. The message is only drawn to the screen for about 4 seconds and disappears (4*TICRATE, 35tics=1s), so it would need to be fast, but not too fast that it doesn't get drawn to the screen in the first place.

Thank you all so much!! <3


Solution

  • I think what you want is the following loop:

    for (int i = 100; i >= 0; i--) {
        alpha = i/100.0f;
        // code here to update the displayed alpha
    }
    

    Dividing by 1.000f is just dividing by 1, which doesn't do anyting except convert from int to float. Dividing by 100.0f will correctly generate a fraction that decrements each time -- the starting value is 100/100.0f = 1.0f, and the ending value is 0/100.0f = 0.0f.

    And you need to update the display within the loop, otherwise you'll only see the final alpha value, not the smooth fade. You should probably also have a delay in the loop, so it doesn't go so quickly that the user can't see the fade.