I want to create a continuous fade in and out.
I'd like to have some function F(time)
that returns values increasing from 0 to 255, then from 255 back down to -255, and repeats, as time progresses.
I want to create a continuous fade in and out.
I'd like to have some function F(time)
that returns values increasing from 0 to 255, then from 255 back down to -255, and repeats, as time progresses.
I know the question has been answered but just for old times sake here is the optimized classic way (works only with fixed steps but takes only 2 bytes ;-) )
//init:
unsigned char value=0;
unsigned char d=1;
//in loop:
value+=d;
if((value==0) || (value==255))
d=-d;
What you're looking for is a periodic function like Sine. Here's how you can use Sine to achieve what you're looking for:
Create a loop counter
Begin your fade loop
Increment your loop counter
fade_amount = 255 * sin(loop_counter)
It's as simple as that. Since sin(loop_counter)
will cycle from -1.0 through 0 to 1.0 and back again, you just multiply it by the maximum value you want.
while(loop_counter >= twoPi) loopCounter -= twoPi
at the end to wrap it back and prevent an eventual overflow.
\$\endgroup\$
Commented
Mar 20, 2012 at 5:46
-1
and 1
exactly, then you get best results if you use fractions of π as your loop_counter
. Eg. loop_counter += PI * 0.1
. The smaller the fraction, the slower the fade in-out.
\$\endgroup\$
You can also use a tweening library to smoothly fade in and out such as cpptweener.