This is just a quick tutorial to explain the different parts of a processing sketch. Hopefully this will have you quickly creating your own processing applications.
If you haven’t already done so – follow the Processing.js getting started tutorial to learn how to run Processing.js in a website.
Now we are going to walk through a couple of examples to get you started in Processing.
Here is the Processing sketch from the previous tutorial:
//Hello World Processing Application
void setup(){
size(500,500);
}
void draw(){
background(200,100,100);
fill(100,200,100);
ellipse(width/2, height/2, 100, 100);
}
As you can see, if we change the fill color – the ellipse color will change.
//Hello World Processing Application
void setup(){
size(500,500);
}
void draw(){
background(200,100,100);
fill(200,200,100);
ellipse(width/2, height/2, 100, 100);
}
We can create animations by having an objects change inside our draw loop.
//Hello World Processing Application
int x;
int y;
void setup(){
size(500,500);
x = width/2;
y = height/2;
}
void draw(){
background(200,100,100);
fill(100,200,100);
ellipse(x, y, 100, 100);
y++;
if(y>height)
y=0;
}
Notice how we use the if statement at the end of the draw function to reposition the ellipse when it goes off the edge. It should look just like this.
If we assign variables for our position and velocity we can use if statements to keep our ball in the bounds of our screen.
//Ball Bounce Processing Application
int x;
int y;
int speedX;
int speedY;
void setup(){
size(500,500);
x = width/2;
y = height/2;
speedX = 8;
speedY = 5;
}
void draw(){
background(200,100,100);
fill(100,200,100);
ellipse(x, y, 100, 100);
y+=speedY;
x+=speedX;
if(y>height){
y = height;
speedY *= -1;
}else if(y < 0){
y = 0;
speedY *= -1;
}
if(x>width){
x = width;
speedX *= -1;
}else if(x < 0){
x = 0;
speedX *= -1;
}
}
Notice how the ball goes slightly out of canvas? That is because our collision detection is set to the center of our circle instead of the edges. Let’s adjust our if statements by including the radius of our circle.
//Ball Bounce
int x;
int y;
int speedX;
int speedY;
int diameter;
void setup(){
size(500,500);
x = width/2;
y = height/2;
speedX = 8;
speedY = 5;
diameter = 100;
}
void draw(){
background(200,100,100);
fill(100,200,100);
ellipse(x, y, diameter, diameter);
y+=speedY;
x+=speedX;
if(y+diameter/2>height){
y = height-diameter/2;
speedY *= -1;
}else if(y-diameter/2 < 0){
y = 0+diameter/2;
speedY *= -1;
}
if(x+diameter/2>width){
x = width-diameter/2;
speedX *= -1;
}else if(x-diameter/2 < 0){
x = 0+diameter/2;
speedX *= -1;
}
}
That’s it for this tutorial – we will have some other tuts up to go into some other computer science topics.