Draw a circle.
void setup() {
size(600, 500);
}
void draw() {
background(200);
circle(100, 100, 20);
}
Things to note: The background() call is in draw()
, not setup()
. This doesn’t matter for a static animation (an “animation” where each call to draw()
draws exactly the same, so that it nothing is changing on the screen), like this.
In this sketch, the circle moves downwards. To do this, we introduce variables x
and y
to hold the circle position. We use a variable for y instead of the literal value 100, because the value changes (varies) from frame to frame.
Each animation frame (each call to draw()
) increments the value of y – it increases the value by one. This causes the circle to be drawn at a different position each time.
float x = 100;
float y = 100;
void setup() {
size(600, 500);
}
void draw() {
background(200);
circle(x, y, 20);
y += 1;
}
Things to note: This sketch also introduces a variable for x, even though it doesn’t every change its value. This use of a variable simply introduces a mnemonic name for the value. It also makes the code easier to read, because x and y are treaded the same way.
Things to note: Here is the pay-off for the fact that the call to background()
is inside draw()
instead of setup()
. Can you see why this is necessary? How does the sketch behave differently if you move the call to background()
back to setup()
, or remove it entirely?
Prepare to add another circle. Rename x
and y
to x0
and y0
, so that we can name the new variables x1
and y1
.
float x0 = 100;
float y0 = 100;
void setup() {
size(600, 500);
}
void draw() {
background(200);
circle(x0, y0, 20);
y0 += 1;
}
Things to note: This sketch behaves the same as the previous sketch. It sets up the code for the next step (adding a second circle), but doesn’t actually take that step. When developing a sketch (or other project), it is useful to break the steps down as small as possible, so that you can test each small change by itself. It is also useful to alternate between: (1) code changes that don’t change the behavior of a sketch, but make the code more flexible, and (2) code changes that add or change behavior.
Copy the code that defines the variables (at the top of the sketch), and the code that uses the variables (inside draw()
), to make another falling circle.
float x0 = 200;
float y0 = 100;
float x1 = 100;
float y1 = 100;
void setup() {
size(600, 500);
}
void draw() {
background(200);
circle(x0, y0, 20);
y0 += 1;
circle(x1, y1, 20);
y1 += 1;
}
Question: How would you extend this sketch to draw three circles, instead of two? How about 100 circles?