This code from Arranging a Line of Items draws a line of shapes. It uses the derivation strategy, to calculate a value for x directly from i each time through the loop.
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
for (let i = 10; i < 20; i++) {
let x = 10 + 50 * i;
let y = 100;
circle(x, 100, 40);
}
}
Note: From here on, the definition of setup()
is not shown. Each of the following code samples assumes that the sketch also contains a setup()
function:
function setup() {
createCanvas(windowWidth, windowHeight);
}
sin
and cos
We can use the sin()
or cos()
functions to make the items swing between the top and bottom of the band, as the index value progresses.
function draw() {
for (let i = 0; i < 10; i++) {
let x = 20 + 50 * i;
let y = 100 + 50 * sin(i);
circle(x, y, 50);
}
}
function draw() {
for (let i = 0; i < 10; i++) {
let x = 20 + 50 * i;
let y = 100 + 50 * cos(i);
circle(x, y, 50);
}
}
Trying to use sin
(or cos
) for both x and y arranges the items on a diagonal line. This is true any time that x and y use the same equation, because then they will have the same value.
function draw() {
for (let i = 0; i < 10; i++) {
let x = 100 + 50 * sin(i);
let y = 100 + 50 * sin(i);
circle(x, y, 50);
}
}
The solution is to use cos
for x
and sin
for y
. These functions are cleverly designed so that using them together this way makes a circle.
Let’s look at just using sin
for y
(instead of x
), and compare that to the code a couple of sketches above that uses cos
for x
.
function draw() {
for (let i = 0; i < 10; i++) {
let x = 100 + 50 * cos(i);
let y = 100 + 50 * i;
circle(x, y, 50);
}
}
Combining cos
for x
with sin
for y
creates a circle.
function draw() {
for (let i = 0; i < 10; i++) {
let x = 100 + 50 * cos(i);
let y = 100 + 50 * sin(i);
circle(x, y, 50);
}
}
There’s two things that may be wrong with this circle, depending on your design intent: (1) it is too small relative to the items that are placed along its edge; and, the items are wrapped around the circle more than once.
The first problem can be addressed by changing the 50
in 50 * cos(i)
and 50 * sin(i)
to a larger number. We will also change the 100
in 100 + 50 * cos(i)
to a larger number, to move the center of the arrangement circle right so that the whole circle stays on the screen.
By default, sin
and cos
repeat every $2\pi$. We need to insure that the number that we putting into them varies from 0 to $2\pi$ by the time the loop is done. Since i
varies from 0 to (just under) 10, i * TWO_PI / 10
varies from 0 to (one step under) TWO_PI
.