# What's the best way to write fade in out function?

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.

• Rephrase your question, so we can make better answers. Mar 20 '12 at 5:09
• Rephrased the question. : ) Mar 20 '12 at 5:20
• This isn't really related to game dev and has a certain lack of details. Mar 20 '12 at 9:51

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;

• I'm sorry if I'm completely missing something, but wouldn't d=-d; result in an unsigned underflow? I'd understand if d were a (signed) char. Mar 21 '12 at 10:57
• Well, it would be simpler to read but no difference actually except the need for extra conversions... Adding the underflowed d (which for '-1' has a value of 255) will act as a -1 to the value 'value'. Mar 21 '12 at 12:59
• I see, of course value will also wrap around and end up one less than before if you just add 255. Thanks for the clarification! Mar 21 '12 at 13:02

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


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.

• What about loop_counter won't it overflow? Mar 20 '12 at 5:35
• @Beast The sine function repeats every 2π radians or 360 degrees, so you could always add something like while(loop_counter >= twoPi) loopCounter -= twoPi at the end to wrap it back and prevent an eventual overflow. Mar 20 '12 at 5:46
• In addition to Davids comment: If you want your values to go through -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. Mar 20 '12 at 7:48

You can also use a tweening library to smoothly fade in and out such as cpptweener.