Is there an easy way to combine sketches if the canvas size and background are the same?
Hi.
If I understand the question well, I guess using if(boolean){} in draw() and using a switch button will do the trick, like:
boolean toggle = true;
void setup() {
size(200, 200);
textSize(15);
}
void draw() {
background(255);
fill(100);
if(toggle) ellipse(mouseX, mouseY, 20, 20); // First sketch
else rect(mouseX, mouseY, 20, 20); // second sketch
fill(0);
rect(140, 10, 55, 25);
fill(255);
text("Toggle", 142, 30);
}
void mousePressed(){
if(mouseX > 140 && mouseY < 35) toggle =! toggle;
}
It depends on how complex the sketches are and if they use the same renderer (default, P2D, P3D).
For simple sketches, you can combine them in draw as noel suggests.
You can also put each sketch in a function, then call them both:
void setup() {
size(400,400);
}
void draw() {
background(192);
sketch1();
sketch2();
}
void sketch1() {
line(random(width), random(height), random(width), random(height));
}
void sketch2() {
float r = random(100);
ellipse(width/2, height/2, r, r);
}
However, if you want two sketches to be accumulating separately and then layered then you will need a PGraphics or PImage for each function (sub-sketch) to draw on and be displayed from.
PGraphics pg1, pg2;
void setup() {
size(400,400);
pg1 = createGraphics(width, height);
pg2 = createGraphics(width, height);
}
void draw() {
sketch1();
sketch2();
}
void sketch1() {
pg1.beginDraw();
pg1.line(random(width), random(height), random(width), random(height));
pg1.endDraw();
image(pg1,0,0);
}
void sketch2() {
float r = random(100);
pg2.beginDraw();
pg2.ellipse(width/2, height/2, r, r);
pg2.endDraw();
image(pg2,0,0);
}
Things can get a lot more complicated if you are incorporating various libraries, multimedia and networking. For example, using the network library you can run two separate sketches and send their data to a third sketch for combined rendering. Or you can run a sketch and send its image output to another sketch for rendering using the Syphon or Spout libraries. There isn’t one simple solution – it depends on what you are trying to do.
I didn’t think about combining sketches. That’s a great idea! Thanks!