It depends a little on what exact effect you want to achieve. For example, do you want them to always be fading in and out, "bouncing" between those states, or would it be more that they are on for a while, then fade out, stay off for a while, then fade in?
And should the fade be at a constant speed, or vary (for example that the lights come on more quickly than they fade out)?
Here is one way to do it if you have 10 fireflies numbered as objects 6-15 (just as an example), and they're meant to stay on and off for some time, but with random variation:
Code: ags
This code uses a helper function clamp() to ensure that we don't try to set Transparency to a value less than 0 or greater than 100. It's very simple:
Code: ags
And should the fade be at a constant speed, or vary (for example that the lights come on more quickly than they fade out)?
Here is one way to do it if you have 10 fireflies numbered as objects 6-15 (just as an example), and they're meant to stay on and off for some time, but with random variation:
#define FIRST_FIREFLY 6 // Object index of first firefly
#define FIREFLY_COUNT 10 // Number of fireflies
#define FIREFLY_FADEIN_SPEED 10 // Fade in over 0.25 seconds (assuming GameSpeed==40)
#define FIREFLY_FADEOUT_SPEED 3 // Fade out over 0.82 seconds
#define FIREFLY_ON_AVG 120 // On average, stay on for 3 seconds
#define FIREFLY_OFF_AVG 240 // On average, stay off for 6 seconds
bool fadingIn[FIREFLY_COUNT]; // Keep track of whether each firefly is fading in or out
function repeatedly_execute_always()
{
for(int i=0; i<FIREFLY_COUNT; i++)
{
Object* firefly = object[FIRST_FIREFLY+i];
if(firefly.Transparency == 0) // Firefly on
{
if(Random(FIREFLY_ON_AVG-1) == 0) // Wait a random number of cycles
{
// Start fading out
fadingIn[i] = false;
firefly.Transparency = clamp(firefly.Transparency+FIREFLY_FADEOUT_SPEED, 0, 100);
}
}
else if(firefly.Transparency == 100) // Firefly off
{
if(Random(FIREFLY_OFF_AVG-1) == 0) // Wait a random number of cycles
{
// Start fading in
fadingIn[i] = true;
firefly.Transparency = clamp(firefly.Transparency-FIREFLY_FADEIN_SPEED, 0, 100);
}
}
else // Continue firefly fading
{
if(fadingIn[i])
firefly.Transparency = clamp(firefly.Transparency-FIREFLY_FADEIN_SPEED, 0, 100);
else
firefly.Transparency = clamp(firefly.Transparency+FIREFLY_FADEOUT_SPEED, 0, 100);
}
}
}
This code uses a helper function clamp() to ensure that we don't try to set Transparency to a value less than 0 or greater than 100. It's very simple:
int clamp(int value, int min, int max)
{
if(value<min) return min;
if(value>max) return max;
return value;
}