topical media & game development

talk show tell print

graphic-processing-algorithm-Ch07-p158-p158.pde / pde



  float [] xp = new float[0]; //used to store the allocated elements
  float [] yp = new float[0];
  int numObjects = 0; //used to count the number of allocated elements
  void setup(){
    size(300,300);
  }
  void draw(){
    background(255);
    for(int i=0; i<xp.length; i++) //draw anything that has been allocated
      rect(xp[i],yp[i],10,10);
  }
  void keyPressed(){
    int k = 0;
    while(true){ //until you find a successful location (i.e. without an overlap)
      boolean overlap = false; //use it to mark overlaps
      float xrand = random(10,width-10); //produce a random possible location
      float yrand = random(10,height-10);
      for(int j=0; j<xp.length; j++){ //go through all the remaining elements
        float distance = dist(xrand,yrand,xp[j],yp[j]); //find distance
        if(distance < 10) overlap = true; //if too short then it will overlap
      }
      if(overlap==false){ //if no overlap then this is a successful location
        xp = append(xp,xrand); //add it to memory
        yp = append(yp,yrand);
        break;
      }
      k++;
      if(k>10000){ // will exit if after 10,000 attempts no space is found
        println(xp.length + " impass"); //warn the user
        break;
      }
    }
    println(numObjects++);
  }
  


(C) Æliens 04/09/2009

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.