I’m trying to change the colors of a few squares whenever the mouse click upon them but can’t figure out a working solution. Here is what I’ve done so far:
I created four values and assigned those to the fills inside void draw().
int color1 = 0;
int color2 = 0;
int color3 = 0;
int color4 = 0;
void setup() {
size(400,400);
background(255);
}
void draw(){
fill(color1);
stroke(0);
rect(20,20,40,40);
fill(color2);
rect(60,20,40,40);
fill(color3);
rect(100,20,40,40);
fill(color4);
rect(140,20,40,40);
}
After this, I writed a void mousePressed() with if statements that checks for the mouse position. I tried the switch/case but with no result. The if statement works only for the fist square; if I try to add more statements it stops working and most importantly it only works if the mouse is placed upon a tiny pixel.
First I’ll address the bigger selection.
Currently you are using pmouseX=20.
First of all, using pmouseX is not reccomended. Use mouseX instead. pmouseX is the previous X position of mouse (in previous frame), while mouseX reffers to current frame.
Secondly you need to define the area where mouse can click on the square.
Look at this image for help
Altho integers CAN store color values, it is hard to memorise the numbers. That’s why there is a color varriable. You can use #RRGGBB to tell the color or color clr = new color(RRR,GGG,BBB)
Now I would like to have more than one color active, i.e. it should remember if something is on or off. Can I keep posting here since it is related or should I open another topic if I can’t find a solution on my own?
Hi Peter, thanks for joining in.
I’m indeed trying to learn classes. This part from your code is interesting:
void setup() {
size(800,800);
ColorRect r1 = new ColorRect(10,10,150,150,color(0,200,0));
ColorRect r2 = new ColorRect(160,160,210,210,color(0,0,200));
rects.add(r2);
rects.add(r1);
}
Can you point out some reference material so I can get a better understanding of the logic?
As of now, I’m trying to implement the boolean suggested by @CodeMasterX on the previous code without success, but I will update about it on the following days.