Processing 3.0 Question - struggling to implement some code

Viewed 32

wondering if anyone can help with this. I have to write some ode using processing 3.0 for college, basically creating a series of circles that appear randomly and change colours etc. Ive got the circles to appear, and they change location on mouse click.

What Im struggling with is, its asked me to have the circles change colour when the mouse button is pressed, where circles to the right are blue and circles to the left of the mouse pointer are yellow? I have no idea how to implement that at all.

Here's what I have so far, any help would be hugely appreciated:

//declaring the variables
float[] circleXs = new float[10];
float[] circleYs = new float[10];
float[] circleSizes = new float[10];
color[] circleColors = new color[10];

void setup() {
size(600, 600);
createCircles();
}
//creation of showCricles function
void draw() {
background(0);
showCircles();
}
//creation of circles of random size greater than 10 but less than 50 - also of white background colour
void createCircles() {
for (int i = 0; i < circleXs.length; i++) {
circleXs[i] = random(width);
circleYs[i] = random(height);
circleSizes[i] = random(10, 50);
circleColors[i] = color(255,255,255);
}
}
void showCircles() {
for (int i = 0; i < circleXs.length; i++) {
fill(circleColors[i]);
circle(circleXs[i], circleYs[i], circleSizes[i]);
}
}
//creating new circles on mouse click
void mouseClicked() {
createCircles();
}
1 Answers

It's not very complicated, you just miss some of the basics. Here are 2 things you have to know to do what you want to do:

  1. You can use mouseX or mouseY to compare coordinates with the current mouse pointer's position.

  2. This would be way cleaner using class, but I am guessing that you are not quite there as you're using a couple arrays to store coordinates instead. But here's the thing with that method: the array's index always refer to the same object. Here your objects are circles, so every array's index n refers to the same circle. If you find a circle which x coordinate is leftward compared to the mouse pointer, you can change that circle's color by modifying the item at the same index but in the circleColors array.

So I added a couple lines to your mouseClicked() method which demonstrate what I just said. Here they are:

void mouseClicked() {
  createCircles();
  
  // here is the part that I added
  // for each circle's X coordinate:
  for( int i = 0; i < circleXs.length; i++) { 

    // if the X coordinate of the mouse is lower than the circle's...
    if( mouseX > circleXs[i]) { 
      // then set it's color to yellow
      circleColors[i] = color(255, 255, 0); 
    } else {
      // else set it's color to blue
      circleColors[i] = color(0, 0, 255); 
    }
  }
}

It should show what you described, or close enough for you to clear the gap.

Hope it helps. Have fun!

Related