Brownian motion.

Brownian motion.

Recording random movement as a continuous line.

 
int num = 2000;
int range = 6;

float[] ax = new float[num];
float[] ay = new float[num]; 


void setup() 
{
  size(640, 360);
  for(int i = 0; i < num; i++) {
    ax[i] = width/2;
    ay[i] = height/2;
  }
  frameRate(30);
}

void draw() 
{
  background(51);
  
  // Shift all elements 1 place to the left
  for(int i = 1; i < num; i++) {
    ax[i-1] = ax[i];
    ay[i-1] = ay[i];
  }

  // Put a new value at the end of the array
  ax[num-1] += random(-range, range);
  ay[num-1] += random(-range, range);

  // Constrain all points to the screen
  ax[num-1] = constrain(ax[num-1], 0, width);
  ay[num-1] = constrain(ay[num-1], 0, height);
  
  // Draw a line connecting the points
  for(int i=1; i<num; i++) {    
    float val = float(i)/num * 204.0 + 51;
    stroke(val);
    line(ax[i-1], ay[i-1], ax[i], ay[i]);
  }
}

Functions Used

stroke()

Sets the color used to draw lines and borders around shapes

Learn More
size()

Defines the dimension of the display window width and height in units of pixels

Learn More
constrain()

Constrains a value to not exceed a maximum and minimum value

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
frameRate

The system variable frameRate contains the approximate frame rate of a running sketch

Learn More
random()

Generates random numbers

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
for

Controls a sequence of repetitions

Learn More
float

Data type for floating-point numbers, e

Learn More
line()

Draws a line (a direct path between two points) to the screen

Learn More
background()

The background() function sets the color used for the background of the Processing window

Learn More