How should I get a connected array of circles (like a worm) to move across my canvas in a straight line?

Viewed 176
void setup(){
  size(800,800);
  background(0);
}

void draw() {
  int[]x= {20,40,60,80,100,120};
  fill (255,0,00);
  for (int i = 0; i <x.length; i ++){
    ellipse (i*6, 100,10,10);
  }
}

I am trying to get the "worm" to move horizontally in a straight line across my canvas. Attached is the "worm." I don't know where to start with the movement because I need to move the whole array at once. Thank you!

2 Answers

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:

Moving an array of values isn't much different from moving a single value.

Let's look at how we'd move a single value:

float x = 0;

void draw(){
  background(0);
  ellipse(x, height/2, 20, 20);

  x++;
}

To move an array of values, you'd do the same thing, but for each index of the array. Something like this:

float[] xArray = {20, 40, 60};

void draw(){
  background(0);

  for(int i = 0; i < xArray.length; i++){
    ellipse(xArray[i], height/2, 20, 20);
    xArray[i]++;
  }
}

Shameless self-promotion: here is a tutorial on animation in Processing, and here is a tutorial on arrays in Processing.

Related