Been trying to create a fading effect, made a separate class for it, everything works fine, except not really. The basic idea was to draw a RectangleShape across the whole screen with a black fillcolor, and an alpha of 0, then the class gradually increases it over a period of time. When I run the thing, that period of time is noticeable, so the class does what it is supposed to do, except I don't see the rectangleshape at all, even though it is being drawn, it is transparent during the whole thing. Tried to do it just within the loop as well, without the class, the issue is the same.
Without class version:
Clock clock;
RectangleShape fade;
fade.setPosition(Vector2f(0,0));
fade.setFillColor(Color(0,0,0,0));
fade.setSize(Vector2f(800,600));
int i=0;
while (window.isOpen())
{
if(clock.getElapsedTime()>seconds(0.04)){
i++;
fade.setFillColor(Color(0,0,0,i));
clock.restart();
}
///other stuff
window.draw(fade);
}
Am I just not supposed to be doing this with a RectangleShape?
Hey I know this is solved but I thought I might share a little more knowledge. If you use linear interpolation you should get a more manageable effect:
int startAlpha = 0;
int endAlpha = 255;
int targetTime = 1000;
sf::Clock timer;
int currentTime = timer.getElapsedTime().asMilliseconds();
int currentAlpha = endAlpha;
if (currentTime >= targetTime)
{
//you are done
}
else
{
currentAlpha = startAlpha + (endAlpha - startAlpha)*currentTime / targetTime;
}
fade.setFillColor(Color(0, 0, 0, currentAlpha));
There's no need to explicitly use certain formats of time. You can use sf::Time more intuitively like so:
// this is outside the loop
int startAlpha = 0;
int endAlpha = 255;
sf::Time targetTime = sf::Seconds(1);
sf::Clock timer;
{
// this is inside the loop
sf::Time currentTime = timer.getElapsedTime();
int currentAlpha = endAlpha;
if (currentTime >= targetTime)
{
// oops: currentAlpha = endAlpha; // make certain that the alpha is at its final destination
//you are done
}
else
{
currentAlpha = startAlpha + (endAlpha - startAlpha) * currentTime / targetTime);
}
// apply alpha to whatever colour is previously set
sf::Color fadeColor = fade.getFillColor();
fadeColor.a = currentAlpha;
fade.setFillColor(fadeColor);
}
Be aware that alpha could be less than the end alpha when the time passes the target time.
EDIT: I realised that my point about alpha passing the final alpha was incorrect.