Mouseclick colorswitch (RGB)

Hello,

I’m trying to figure out how to switch the color of the screen multiple times by using mouseclick/ mousepressed.

The background has to switch from black to red, then blue, then green, (and then back to red.)
This has to be done manualy by clicking.
I saw that multiple questions almost the same, but not quite what i was looking for.

Greetings, Derk.

Number your colors.
Black can be 0.
Red can be 1.
Blue can be 2.
And so on.

Use a number to remember what the number of the current color is.

Now when the mouse is pressed,
Go to the next number, and thus the next color.
If you’ve gone to a number that doesn’t have a color,
go back to 1, for red. (or whatever!)

When you draw the screen,
If the number is 0, draw a black screen.
If the number is 1, draw a red screen.
And so on.


Now that we have the plan detailed above, we can convert it almost directly into code!

// Have a number that remembers the current color.
int cur = 0;

// When the mouse is pressed...
void mousePressed(){
  // Go to the next color.
  cur = cur + 1;
  // If we're at a color that isn't a number,
  if( cur == 5 ){
    // Go back to 1, red
    cur = 1;
  }
}

I will leave writing the setup() and draw() functions to you! It shouldn’t be too hard if you’ve seen any other examples…

Try putting it all together and post the code of your attempt if you need more help!

1 Like

OpenProcessing.org/sketch/473642

1 Like

Hey guys!

Thanks for helping me, you did really help me out.

I still have a question about the: “int curt = 0;”
Maybe i’m tired, but, how do you implement the colors? :c

greets,
Derk

1 Like

We were trying to get you to understand the concept of enumeration. Instead of checking what the current color’s RGB values are, you can just do one check for one number which is the number of what the current color is.

Initially this was an attempt to get you to write several if statements:

if( cur == 0 ){
  background(0);
}
if( cur == 1 ){
  background(255,0,0);
}
// ... etc

And then afterwards we would point out that, by cleverly using the cur variable and an ARRAY, you could just do away with all the checking logic completely:

int cur = 0;
color[] colors = { color(0), color(255, 0, 0), color(0, 255, 0), color(0, 0, 255) }; 

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

void draw(){
  background( colors[ cur ] );
}

void mousePressed(){
  cur++;
  cur%=colors.length;
  if( cur == 0 ) cur = 1;
}
2 Likes

Oh, this looks cool!

I have one question tho, what does: cur%=colors.length; mean?
It looks like it makes the loop, from blue back to red, but i’m not sure.
Does the % have anything to do with the string?
Is it neccesery to use it in combination with the string?

Thanks a lot, kind sir! ; D

Processing.org/reference/modulo.html

1 Like