Lesson 40 – Arrays

by golan @ 1:52 pm September 28, 2011

“Flocking” simulation — actually, 100 drunks:

float   pxArray[]; // declaration
float[] pyArray;
int nDrunks = 100;
 
void setup() {
  size(400, 400);
 
  pxArray = new float[nDrunks]; // ALLOCATION
  pyArray = new float[nDrunks];
 
  for (int i=0; i<nDrunks; i++) {
    pxArray[i] = width/2; // assignment
    pyArray[i] = height/2;
  }
}
 
 
void updateFlockingSimulation() {
  for (int i=0; i<nDrunks; i++) {
    pxArray[i] += random(-4, 4);
    pyArray[i] += random(-4, 4);
  }
}
 
void renderFlockingSimulation() {
  for (int i=0; i<nDrunks; i++) {
    ellipse(pxArray[i], pyArray[i], 20, 20);
  }
}
 
void draw() {
  background(128);
  updateFlockingSimulation();
  renderFlockingSimulation();
}

A case where the arrays are set with specific values at the start:

float xPoints[] = {
  280.0, 289.0, 134.0, 64.0, 151.0
};
float yPoints[] = {
  74.0, 205.0, 260.0, 194.0, 61.0
};
 
 
void setup() {
  size (400, 400);
  smooth();
}
 
void draw() {
  background(126);
  beginShape();
  for (int i=0; i<5; i++) {
    float px = xPoints[i] + 30*noise(i + millis()/200.0);
    float py = yPoints[i] + 30*noise(i + millis()/313.0);
    vertex(px,py);
 
  }
  endShape(CLOSE);
}

»

TrackBack URI

Leave a comment

You must be logged in to post a comment.

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2017 CMU Electronic Media Studio II, Fall 2011, Section A | powered by WordPress with Barecity