Quantcast
Viewing all articles
Browse latest Browse all 40524

Making a value increase then decreases

If you really wanted to use just one variable you could do something like this:

x++;
if(x>255) x = -254;

and then when you want to use the value, use abs(x) to get the absolute value ... but it's not a good way to do it (not easy to follow code)!

Or you can make the code a bit more concise if you use an int that is always 1 or -1 instead of a boolean ... e.g. another way to write bakercp's example:

int brightness = 0;
int brightnessDirection = 1;

void draw(){

        if(brightness >= 255 || brightness <= 0) brightnessDirection *= -1;
        brightness += brightnessDirection;

        // Do something with brightness
}

Though I do recognise that concise isn't always what you want in example code to assist learning.

Or as I mentioned you can use Sine to fluctuate the value:

brightness = ofMap(sin(ofGetFrameNum() * 0.01),-1,1,0,255);

So we're getting the sine value of the current frame number multiplied by a value (0.01 here) that controls the speed that we want the brightness value to modulate. Then because Sine always returns a value between -1 and 1 we map that to our desired output range, 0 to 255. This isn't exactly an answer to your question because it will produce a different result - a more gradual rate of change as it nears the limits instead of a sharp change to a new constant rate. But in a lot of situations it can produce a nicer effect.


Viewing all articles
Browse latest Browse all 40524

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>