You posted your code and asked for some help. For more pineapples, in future posts, format your code properly. The button to do it right looks like this: </>
class Timer {
int time;
int duration;
Timer() {
duration = 100;
reset();
}
void reset() {
time = millis() + duration;
}
boolean alarm() {
if ( millis() > time ) {
time = millis() + duration;
return true;
}
return false;
}
}
// Position and size of the square.
float x,y,s;
// Color of the square.
color c;
Timer timer = new Timer();
void setup() {
size(700, 500);
timer.duration = 3000;
newSquare(); // Make initial square.
}
void draw() {
background(0);
fill(c);
rect(x, y, s, s);
if( timer.alarm() ){
newSquare();
}
}
void mousePressed(){
if( overSquare() ){
newSquare();
}
}
boolean overSquare(){
return( x < mouseX && mouseX < x + s && y < mouseY && mouseY < y + s );
}
void newSquare() {
s = random(5,min(width,height));
x = random(0, width - s);
y = random(0, height - s);
c = color( random(255), random(255), random(255) );
timer.reset();
}
Here we see a finished example of what you want. Notice that there is a simple Timer class that has an alarm() function that returns true 3000ms (3 seconds) after it has been reset. The bulk of the work is now done by the newSquare() function, which sets the global variables that determine where and how big and what color the square is to new values. Making a new square also resets the timer.
If the user clicks, the mousePressed() function triggers. If the click was over the square (and there is a function to determine this based on where the click was and where the square is and how big the square is), then the newSquare() function is called to make a new square (which then also resets the timer).
Finally, if the timer’s alarm goes off (and this is checked for in draw()), then the newSquare function is also called. Thus a new Square happens every three seconds in any case.
I would have you pay special attention to the names of the variables I am using for the square. The x positon is x. The y position is y. The size is s. Before, you were using x for the square size! That was a little confusing.
Notice that there is no longer a call to set the framerate() very low. This is because the timer is using calls to millis() to determine when three seconds have passed - it no longer relies on a very low frame rate.
Please take some time to understand this example completely!