Hi all - is there any way I can make some section of code in draw() only after a certain event has happened?
For example can I only start drawing things after a mouseclick or if the user presses a set key?
Thanks in advance
Hi all - is there any way I can make some section of code in draw() only after a certain event has happened?
For example can I only start drawing things after a mouseclick or if the user presses a set key?
Thanks in advance
Yes, just use a boolean.
boolean start = false;
void setup() {
size(500, 400);
}
void draw() {
if (start) {
ellipse(100,100,50,50);
}
}
void mousePressed() {
start = true;
}
Thank you so much. I liked my game much more because of your code. Thank you again!
I appreciate this, but this must surely slow down the program somewhat?
? I mean… sure… that‘s how programing works… you add functionality and it makes more things happen, which obviously means finishing a Frame takes longer…
But if you mean that you will notice the difference… no. It‘s just an if statement. The background(0); function alone goes through a Ton of if statements, just like any function you can think of uses on average ~ 50 if statements (not themselves, but the functions they call also count).
boolean is one idea.
When you have different screens (and not only two) you can use an int variable, in the forum mostly referred to as state.
int state = 0;
....
if (state==0){
// screen 1
}
else if (state==1){
// screen 2
}
else if (state==2){
// screen 3
}
Yes – single if statements themselves are basically free – like putting a grain of sand in a truck. If you add many millions of grains of sand, you could eventually slow the truck down, but it will take a lot – it is never worth counting them individually. When in doubt, test.
Instead of how many ifs, the key to performance is how much (is the if in a for loop?) of whatever is inside them – including the if condition statement. On my laptop this sketch runs smoothly even when testing 2,147,483,647 if statements per frame, 60fps.
On the other hand, when you switch to a modulo or a random number inside each if condition, the sketch might start to slow down a lot after a mere 10,000,000 ifs per frame or so… only 60,000,000 ifs per second. Now you are filling your truck with gravel, or pebbles. Still not worth counting individually – but it takes fewer to fill up.
/**
* How Many Ifs
* 2019-12 Processing 3.4
* https://discourse.processing.org/t/wait-until-syntax/15838/3
*/
int ifs = 10;
void draw() {
background(0);
if (frameCount%180==0) ifs *= 10;
if (ifs > 1000000000 || ifs < 0) ifs = MAX_INT;
int x=0;
int rnd = (int)random(ifs);
for (int i=0; i<ifs; i++) {
if (i>rnd) { // simple test, full speed
// if (ifs%(i+1)==0) { // slightly harder math, eventually slows
// if (random(1)>0.5){ // random(), much heavier lift, eventually crawls
x++;
}
}
text(frameRate, 10, 25);
text(str(ifs) + "\n~ifs/frame", 10, 45);
}