Example
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com

// Example 5-7: "Bouncing" color

// Two variables for color.
float c1 = 0;      
float c2 = 255;    

// Start by incrementing c1.
float c1dir = 0.1;  
// Start by decrementing c2.
float c2dir = -0.1; 

void setup() {
  size(200,200);
}

void draw() {
  noStroke();
  
  // Draw rectangle on left
  fill(c1,0,c2);
  rect(0,0,100,200);

  // Draw rectangle of right
  fill(c2,0,c1);
  rect(100,0,100,200);

  // Adjust color values
  c1 = c1 + c1dir;
  c2 = c2 + c2dir;
  
  // Instead of reaching the edge of a window, these variables reach the "edge" of color:  
  // 0 for no color and 255 for full color.  
  // When this happens, just like with the bouncing ball, the direction is reversed.

  // Reverse direction of color change 
  if (c1 < 0 || c1 > 255) {
    c1dir *= -1;
  }

  if (c2 < 0 || c2 > 255) {
    c2dir *= -1;
  }
}








  • http://www.solundrian.com Rosie Wood

    really interesting, I never thought of doing that…

  • http://subpixels.com subpixel

    This code does not correct for stepping over the boundaries.

    When the code reaches the first boundary (c1 == 255.1, c2 == -0.1), both c1dir and c2dir are negated, but c1 and c2 retain the values 255.1 and -0.1 which will be passed to fill() on the next call to draw(). Similarly for each colour variable heading in the other direction.

    Including “c1 = c1 + c1dir;” in the first conditional will repeat the boundary value, so a nice crisp bounce is produced with “c1 = c1 + 2 * c1dir;” or equivalent code.

    I might also suggest using variable names other than c1dir and c2dir since they are rates of change, not merely (or perhaps not even) “directions”.

    A similar problem exists in the “bouncing ball” (Example 5-6) code, but is arguably less “critical” (the ball doesn’t “bounce” until the centre passes the edge anyway). The bouncing ball problem is one that I still find tricky – for example, a bouncing ball under “gravity” that eventually comes to rest, and that looks good, is not so easy!

  • Dhruv

    why dont the colors become black and white at the extreme instead remain separate and become purple ? (0,0,0) would be black wouldn’t it ?

  • http://www.learningprocessing.com Daniel Shiffman

    The color is never (0,0,0). As the R value (‘c1′) counts down, the B value (‘c2′) counts up. So they cross at ~127 (127,0,127), which is purple.