Search code examples
javaprocessing

How to change RGB colour depending on mouse position in Processing3?


I am writing a little program in Processing3 that enables me to change the background to a specific colour RGB code stored in arrays. Each vale for R, G and B is stored in a separate array.

Changing the mouse horizontal position changes the colour of the background.

However this solutions code is quite repetitive, and there is a lot of if/else statements. I want to use a for() loop to simplify the code and make it less repetitive. However, i am struggling to include the mouse position variable in the for() loop. Is there to simplify this code using a for() loop and somehow map the mouse position to access array items? This is the code I have right now:

int[] r = {255,249,240,233,227};
int[] g = {115,138,157,173,187}; 
int[] b = {0,18,63,94,120};

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

void draw() {
    int x = mouseX;

    if(x >= 0 && x <=100) {
        background(r[0], g[0], b[0]);
    }

    else if (x >= 101 && x <= 200){ 
        background(r[1], g[1], b[1]);
    }

    else if (x >= 201 && x <= 300){ 
        background(r[2], g[2], b[2]);
    } 
    else if (x >= 301 && x <= 400){ 
        background(r[3], g[3], b[3]);
    }  
    else {
        background(r[4], g[4], b[4]);
    }
}

I wish to simplify the code to something more like this:

 int[] r = {255,249,240,233,227};
 int[] g = {115,138,157,173,187}; 
 int[] b = {0,18,63,94,120};

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

 void draw() {

    for(int i=0; i<r.length; i++) {
        background(r[i],g[i],b[i]);
    } 
 }

However, I don't know how to change this code in a way, that the background colour would change depending on mouse horizontal position, as it is shown in the first example.

Thank you for your reply and help!


Solution

  • If your steps between your different values are 100, then you can just divide the input X value by 100. Integer division will take care of the rest.

    The if statement is just to make sure it stays within the bounds of your array.

    int mouseX = ...;
    int i = mouseX / 100;
    
    if(i < r.length && i < g.length && i < b.length)
    {
      background(r[i], g[i], b[i]);
    }