tags:

views:

256

answers:

3

I'm trying to make a flashing object, i.e., increment it's alpha value from 0 to 255 (gradually) and then back down to 0, and repeat.

Is there a way I can do this without using some boolean? Getting it to increment is easy:

alpha = time.elapsed()%256;

But what's a nice way to get it to count back down again after that?

+12  A: 

Maybe you could do it this way:

alpha = abs((time.elapsed() % 510) - 254);
sth
+1 had to stare at that for a second to wrap my brain around it
Dave DeLong
I think it should be 511 and 255, no? 256 shouldn't be included. Anyway, knew there had to be a trick like this, I just forgot about `abs`ing it. Thanks! Works great.
Mark
This will start at abs(0 % 510 - 254) = 254. That seems pretty awkward.
Joren
Oh no... then 255 repeats twice... should be 510 and 255 then?
Mark
@Johan: You could add a `+254` inside the modulo to have it start at 0.
sth
@Mark: I don't see where it includes 256 or where 255 repeats... For which numbers does it give wrong results?
sth
Ah... nvm, you're right sth. It just looks funny because it starts at 254. I'm just confusing myself.
Mark
+4  A: 

abs(((x + 255) % 510) - 255) will go linearly from 0 to 255 for x between 0 and 255, and linearly from 255 to 0 for x between 255 and 510. Then it repeats (with period 510 of course).

Joren
I guess technically this is the right answer since I said increment first. sth's answer starts with decrementing, but it's fewer operations, so I actually prefer it. Either way is fine ;)
Mark
+13  A: 

How about using a sin function, that way the fading is more pleasant and you'll get what you want.

Tom
Code example? (a)
Mark
`alpha = static_cast<int>(sin((time.elapsed()%10)*(M_PI/10))*255);`? I think? 10 can be replaced with whatever interval you wish, and optimally you would replace `M_PI/10` with a constant (e.g. `const double frac = M_PI/10;`)
GRB
Hrm... you're right, I think this does look ever so slightly better. A period of 1000ms is pretty decent.
Mark