I am trying to get into creative coding mainly for creating live visuals. I have recently stumbled upon this great website called https://www.openprocessing.org/ where people can share their creations.
I have attached code below for creating two moving circles but I am having trouble understanding how the creator went about doing so, If anyone could explain to me how the for loop is working as well as how the x += 0.006; y += 0.006; if (x > TWO_PI) {x = 0;}
section works, it would be greatly appreciated. The use of sin
, cos
and the Two_PI functions has me puzzled. Here is a link to the original code:
https://www.openprocessing.org/sketch/467333
//comment
float x = 0;
float xx = 0;
float y = 0;
float yy = 0;
float sizecircle = 250;
void setup() {
size (800, 650);
frameRate (60);
strokeWeight (1);
stroke (223, 170, 22);
}
void draw() {
background (51, 51, 51);
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line (350 + sin(x+i) * sizecircle, 275 + cos(y+i) * sizecircle, 450 + cos(xx+i) * sizecircle, 375 + sin(yy+i) * sizecircle);
}
x += 0.006;
y += 0.006;
if (x > TWO_PI) {
x = 0;
}
if (y > TWO_PI) {
y = 0;
}
xx += 0.002;
yy += 0.002;
if (xx > TWO_PI) {
xx = 0;
}
if (yy > TWO_PI) {
yy = 0;
}
}
The unit of the angle for sin
and cos
is Radian. 360° are 2*PI, this is the reason for TWO_PI
.
The variables x
, y
, xx
and yy
are incremented for 0.0 to 2*PI. If they reach 2*PI, they start form 0.0 again.
With the following code will draw lines from a center point (cx
, cy
) to 100 points around a circle with radius r
.
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line(cx, cy, cx + cos(i)*r, cy + sin(i)*r);
}
The trick in the code of the question is that the lines are connection the points around 2 circles, which are rotating opposite direction:
line(cx1 + sin(i)*r, cy1 + cos(i)*r,
cx2 + cos(i)*r, cy2 + sin(i)*r);
Note, that the order of sin
and cos
is swapped for the start point in compare to the end point, this causes that the circles are rotating opposite directions.
The different rotation speed is caused by the different constants 0.006
respectively 0.002
.
By the way, the code can be simplified, because x == y
and xx == yy
. It is sufficient to use 2 angles in the range [0, TWO_PI
]:
float a1 = 0;
float a2 = 0;
float sizecircle = 250;
void draw() {
background (51, 51, 51);
for (float i = 0; i < TWO_PI; i += TWO_PI/100) {
line (350 + sin(a1+i)*sizecircle, 275 + cos(a1+i)*sizecircle,
450 + cos(a2+i)*sizecircle, 375 + sin(a2+i)*sizecircle);
}
a1 += 0.006;
a2 += 0.002;
}
Since sin(x) == sin(x + TWO_PI*n)
and cos(x) == cos(x + TWO_PI*n)
(n is an integral number), it is not necessary to "reset" the angles.