Store the current positions of the worm in a global array, where the head is the first position.
int[] x= {30,24,18,12,6,0};
int step = 6;
Change the position in every frame by the distance between 2 parts of the worm. Shift the current positions in the array in a loop:
draw() {
.....
for (int i = x.length-1; i > 0; --i ){
x[i] = x[i-1];
}
x[0] += step;
.....
}
Chang the direction if the end of the window or the begin of the window is reached, by the head of the worm:
if ( x[0] >= width || x[0] < 0)
step *= -1;
Draw the worm in the reverse order:
for (int i = x.length-1; i >= 0; --i ){
ellipse(x[i], 100, 10, 10);
}
The full code may look like this:
void setup(){
size(200,200);
}
int[] x= {30,24,18,12,6,0};
int step = 6;
void draw() {
background(0);
fill (255,0,00);
for (int i = x.length-1; i >= 0; --i ){
ellipse(x[i], 100, 10, 10);
}
for (int i = x.length-1; i > 0; --i ){
x[i] = x[i-1];
}
x[0] += step;
if ( x[0] >= width || x[0] < 0)
step *= -1;
}
See the preview:
