Today:
To play audio, we can use the Processing Sound library.
import processing.sound.*;
SoundFile song;
void setup(){
size(200,200);
song = new SoundFile(this, "song.mp3");
song.play();
}
void draw(){
}
void mousePressed(){
if (song.isPlaying()){
song.pause();
} else {
song.play();
}
}
The translate() function allows objects to be moved to any location within the window. The first parameter sets the x-axis offset and the second parameter sets the y-axis offset.
Simple example
//Processing 4 reference
size(400, 400);
translate(120, 80);
rect(0, 0, 220, 220);
More complex example
//example from Processing 4.0 documentation
float x, y;
float dim = 80.0;
void setup() {
size(640, 360);
noStroke();
}
void draw() {
background(102);
x = x + 0.8;
if (x > width + dim) {
x = -dim;
}
translate(x, height/2-dim/2);
fill(255);
rect(-dim/2, -dim/2, dim, dim);
// Transforms accumulate. Notice how this rect moves
// twice as fast as the other, but it has the same
// parameter for the x-axis value
translate(x, dim);
fill(0);
rect(-dim/2, -dim/2, dim, dim);
}
Rotate is used to rotate the entire drawing window. It is often useful to use rotate in combination with translate.
float angle;
float jitter;
void setup() {
size(640, 360);
noStroke();
fill(255);
rectMode(CENTER);
}
void draw() {
background(51);
// during even-numbered seconds (0, 2, 4, 6...)
if (second() % 2 == 0) {
jitter = random(-0.1, 0.1);
}
angle = angle + jitter;
float c = cos(angle);
translate(width/2, height/2);
rotate(c);
rect(0, 0, 180, 180);
}
The push() and pop() functions allow for more control over transformations. The push function saves the current coordinate system to the stack and pop() restores the prior coordinate system.
I like to think of this as laying down and picking up layers.
//Processing 4 reference
size(400, 400);
fill(255);
rect(0, 0, 200, 200); // White rectangle
pushMatrix();
translate(120, 80);
fill(0);
rect(0, 0, 200, 200); // Black rectangle
popMatrix();
fill(100);
rect(60, 40, 200, 200); // Gray rectangle
Increases or decreases the size of a shape by expanding and contracting vertices. Objects always scale from their relative origin to the coordinate system. Scale values are specified as decimal percentages. For example, the function call scale(2.0) increases the dimension of a shape by 200%. Transformations apply to everything that happens after and subsequent calls to the function multiply the effect. For example, calling scale(2.0) and then scale(1.5) is the same as scale(3.0). If scale() is called within draw(), the transformation is reset when the loop begins again. Using this function with the z parameter requires using P3D as a parameter for size(), as shown in the third example above. This function can be further controlled with pushMatrix() and popMatrix().
//Processing 4 reference
size(400, 400);
rect(120, 80, 200, 200);
scale(0.5);
rect(120, 80, 200, 200);
Read Chapter 17, text
Read Chapter 20, sound