Random Walkers with tails

edited March 2016 in Questions about Code

Hey! Since a few days i am studying Shiffmans „The Nature Of Code“

I am currently experminenting with random walkers. But these walkers are currently just simple ellipses that walk through my canvas. Now i want to give them a tail, to make them look like worms. :-)

Does anyone know how i can do that?

color bg = #EA4D40;
color fg = #27348B;

Walker[] walkers = new Walker[100];
float a;

void setup() {
  size(540, 540, P2D);
  background(bg);
  for (int i =0; i < walkers.length; i++) {
    walkers[i] = new Walker();
    noStroke();
  }
}

void draw() {
  background(bg);
  fill(fg);
  translate(width/2, height/2);
  for (int i =0; i < walkers.length; i++) {
    walkers[i].move();
    walkers[i].display();
  }
}

class Walker {
  float x=0;
  float y=0;
  float stepx;
  float stepy;

  Walker() {
  }

  void move() {
    int stepx = int(random(3))-1; 
    int stepy = int(random(3))-1;

    x = x + stepx;
    y = y + stepy;
  }


  void display() {
    ellipse(x, y, 2, 2);
  }
}

Answers

  • edited March 2016 Answer ✓

    Here you go.

    color bg = #EA4D40;
    color fg = #27348B;
    
    Walker[] walkers = new Walker[100];
    float a;
    
    void setup() {
      size(540, 540, P2D);
      background(bg);
      for (int i =0; i < walkers.length; i++) {
        walkers[i] = new Walker();
        noStroke();
      }
    }
    
    void draw() {
      background(bg);
      fill(fg);
      translate(width/2, height/2);
      for (int i =0; i < walkers.length; i++) {
        walkers[i].move();
        walkers[i].display();
      }
    }
    
    class Walker {
      float x=0;
      float y=0;
      float stepx;
      float stepy;
      ArrayList<PVector> tail;
    
      Walker() {
        tail = new ArrayList();
      }
    
      void move() {
        if (tail.size()>30) tail.remove(0);
    
        int stepx = int(random(3))-1; 
        int stepy = int(random(3))-1;
    
        x = x + stepx;
        y = y + stepy;
    
        tail.add( new PVector( x, y ) );
      }
    
    
      void display() {
        stroke(255);
        for (int i = 0; i<tail.size ()-1; i++) {
          line(tail.get(i).x, tail.get(i).y, tail.get(i+1).x, tail.get(i+1).y );
        }
        noStroke();
        ellipse(x, y, 2, 2);
      }
    }
    

    The trick is to remember a lot more information about each Walker - we use an ArrayList to remember the last N (N=30 is a good value) positions a Walker was in, and we draw the tail as a line connection all those previous positions. Since your Walkers are already objects, we can make this change in the class and it applies to all your Walkers.

    Enjoy!

  • Very nice! Many, many thanks!

Sign In or Register to comment.