Loading...
Logo
Processing Forum

Color change logic

in Programming Questions  •  1 year ago  
I'm working on a way to make a javaScript color changer and I'm using Processing for testing because it is easy to test out logic fast. I would like to make a color changer that just uses if statements with basic data types (boolean, int) so that it is easy to use cross language (so that means no hue() or anything). So far I have the code below which isn't too bad for what I have in mind but seems to miss a few colors (like green most notably). Does anyone know of a nice way to set up a color changer that avoids white / gray / black and hits all of the hues?

NOTE: Heads up for EPILEPSY if you are sensitive to it! I set the speed to be fairly slow but heads up anyway, I don't know too much about the condition but I know that flashing lights can be bad for it.


int speed = 5;
boolean[] cGo = new boolean[3];
boolean[] cDir = new boolean[3];
int[] channel = new int[3];

void setup() {
  size(400, 400);
  for (int i = 0; i < 3; i++) cDir[i] = true;
  cGo[0] = true;
}

void draw() {
  for (int i = 0; i < 3; i++) {
    if (cGo[i]) {
      if (cDir[i]) channel[i] += speed;
      else channel[i] -= speed;
      if (channel[i] <= 0) {
        channel[i] = 0;
        cDir[i] = !cDir[i];
      }
      if (channel[i] >= 255) {
        channel[i] = 255;
        cDir[i] = !cDir[i];
      }
      if (i < 2 && channel[i] > 128) cGo[i+1] = true;
    }
  }
  background(channel[0], channel[1], channel[2]);
}

Replies(3)

You might find this  Javascript tutorial on color cycles (that I wrote a few yeas ago) helpful.  It's not Java, but the basic technique can be easily translated, and the underlying concepts are useful to know.

In your code, you could use something like this (borrowing the essential concept from my tutorial):

Copy code
  1. void draw() {
  2.  float secs = millis()*.001;
  3.   int r = (int) (sin(secs)*128+128);
  4.   int g = (int) (sin(secs + 2)*128+128);
  5.   int b = (int) (sin(secs + 4)*128+128);
  6.   background(r, g, b);
  7. }

Ah, that's so much shorter that I almost feel dumb for not having thought of sin, ha ha ha. I was wondering what the idea behind +2 and +4 was? I tried +TWO_PI/3 and +TWO_PI*2/3 and got a very similar result.

Nice tutorial by the way.
Yeah, 2 and 4 are just approximations for those more accurate values (that produce a slightly less saturated result).  I use 'em when I'm lazy.  I got into the computer automation business due to extreme sloth.