<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with remove() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=remove%28%29</link>
      <pubDate>Sun, 08 Aug 2021 19:23:10 +0000</pubDate>
         <description>Tagged with remove() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggedremove%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>clearing an ArrayList</title>
      <link>https://forum.processing.org/two/discussion/28120/clearing-an-arraylist</link>
      <pubDate>Thu, 20 Sep 2018 05:16:28 +0000</pubDate>
      <dc:creator>eduzal</dc:creator>
      <guid isPermaLink="false">28120@/two/discussions</guid>
      <description><![CDATA[<p>I've around this issue a few times.
I have a particle system that contains an ArrayList of particles.
I use a separate window for the interface programmed using Control P5.</p>

<p>usually my particle system lies under a boolean, and that boolean is activated/deactivated by a cp5 toggle.
every time i toggle it to false, i want the ArrayList inside the particle system to be cleared, so the particle system starts fresh from zero instead of a simple interruption it's runtime.</p>

<p>so i put a ps.particles.clear(); in the toggle false condition. everytime it crashes and I get IndexOutOfBoundsException.
it also happened to me with a bang and a button.</p>

<p>what is the most efficient way to really clear an ArrayList?</p>

<p>here is the code with whats going on.</p>

<p>main code</p>

<pre><code>import controlP5.*;
ControlFrame cf;
RingSystem r;

boolean isRing = false;

void settings(){
   size(600,600);
}    

void setup(){

     //CONTROLP5
     cf =new ControlFrame(this, 400, displayHeight, "MENU", width, height);

     //RING SETUP
     cPos=new PVector(width/2, height/2, 0);
     r=new RingSystem(cPos);
}

void draw(){
  if (isRing) {
    if (frameCount%30==0) r.addRing();
    r.display();
  }
}
</code></pre>

<p>Ring System</p>

<pre><code>class RingSystem{
 ArrayList&lt;Ring&gt; rings;
 PVector origin;
 RingSystem(PVector _origin){
   rings=new ArrayList&lt;Ring&gt;();
   origin=_origin.copy();
 }

 void addRing(){
  rings.add(new Ring(origin)); 
 }

 void display(){
   for(int i=rings.size()-1; i&gt;0; i--){
    Ring r=rings.get(i);
    r.update();
    r.display();
    if(r.isDead()){
     rings.remove(i); 
    }
   }
 }
}
</code></pre>

<p>Ring/Particle</p>

<pre><code>class Ring {
  PVector origin;
  float dim=0;
  float dimMax=400;
  float life=0;
  float alpha;

  Ring(PVector _origin) {
    origin=_origin.copy();
  }

  void update() {
    life++;
    //origin.y++;
    //dim=cos(radians(life))*life;
    dim=life;
    alpha=map(life,height*2,0,0,255);
  }

  void display() {
    pushMatrix();
    stroke(0, 255, 255,alpha);
    strokeWeight(6);
    noFill();
    translate(origin.x, origin.y, origin.z);
    //rotateX(radians(90));
    ellipse(0, 0, dim, dim);
    popMatrix();
  }

  boolean isDead() {
    if (life&gt;height*2) {
      return true;
    } else {
      return false;
    }
  }
}
</code></pre>

<p>Control Frame</p>

<pre><code>public class ControlFrame extends PApplet {

  ControlP5 cp5;
  Object parent;

  public void setup() {
    cp5 = new ControlP5(this);  

    cp5.addToggle("ringToggle")
      .setPosition(160, 50)
      .setSize(80, 80)
      .setValue(false)
      ;
}
  void ringToggle(boolean toggle) {
    if (toggle==true) {
      isRing=true;
    } else {
      isRing=false;

      r.removeAll(rings);
      for (int i=0; i&lt;r.rings.size(); i++) {
        Ring ri=r.rings.get(i);
        r.rings.remove(i);
      }
    }
  }
</code></pre>

<p>}</p>
]]></description>
   </item>
   <item>
      <title>match 3 removing from ArrayList</title>
      <link>https://forum.processing.org/two/discussion/28064/match-3-removing-from-arraylist</link>
      <pubDate>Fri, 22 Jun 2018 03:35:07 +0000</pubDate>
      <dc:creator>ctrembla</dc:creator>
      <guid isPermaLink="false">28064@/two/discussions</guid>
      <description><![CDATA[<p>I'm trying to create a match 3 &amp; made a check function that works &amp; tell me when there are 3 in a row. I tried giving each one a float but when I go to remove the letters assign to each i that met nothing happened. Can anyone tell me why?
here the code for the block.</p>

<p>`class block{
  float x,y,w,type,a,d,c;
  boolean first, second = false;
  block(float x, float y, float w, float type){
    this.x = x;
    this.y = y;
    this.w = w;
    this.type = type;
  }
  void show(){
    if (type == 0){fill(255,0,0);}
    if (type == 1){fill(0,255,0);}
    if (type == 2){fill(0,0,255);}
    if (type == 3){fill(255,0,255);}
    if (type == 4){fill(255,255,0);}
    rect(x,y,w,w);
  }</p>

<p>void update(){
    textSize(15);
    for (int i = 0; i &lt; Block.size(); i++){
      block b = Block.get(i);
      if (b.type == type){
        if (b.x == x &amp;&amp; b.y == y){
          c = i;
        }
        if (b.x + 50 == x &amp;&amp; b.y == y){
          first = true;
          text("1",15,15);
          a = i;
        }
        if (b.x + 100 == x &amp;&amp; b.y == y &amp;&amp; first == true){
          second = true;
          text("2",15,30);
          fill(255,0,0);
          rect(x-100,y,150,10);
          d = i;
        }
      }
    }
    Block.remove(a);
    Block.remove(d);
    Block.remove(c);
  }
}`</p>
]]></description>
   </item>
   <item>
      <title>How to understand what is slowing down the code on many iterations?</title>
      <link>https://forum.processing.org/two/discussion/27944/how-to-understand-what-is-slowing-down-the-code-on-many-iterations</link>
      <pubDate>Tue, 08 May 2018 23:59:27 +0000</pubDate>
      <dc:creator>bug_ugly</dc:creator>
      <guid isPermaLink="false">27944@/two/discussions</guid>
      <description><![CDATA[<p>I have a very big code with multiple classes which creates a simulation of artificial creatures. It contains an evolution algorithm which at the end of each generation saves several copies of the best individuals and then recreates an entirely new generation using their neural networks with added mutations. On the creation of a new generation, the old one is wiped.
However, with each generation, it loads the next generation slower practically stopping on gen 4 or 5 (the number of agents doesn't change from generation to generation). At that point, it just basically freezes after I call the "evolveWorkers()" function. Is there any tool which I can use in order to find the function on which it gets stuck?</p>

<p>Thanks in advance to anyone who replies.</p>

<p>And in case you can help me, here are some bits of code which I think might be creating a problem, if you want a function of something in particular I am happy to share it too.:</p>

<pre><code>void evolveWorkers() {
    int j = 0;
    ArrayList &lt;Alien&gt; elites = new ArrayList &lt;Alien&gt;(); //creating an array list where to store the best fit 
    elites = returnFit();

    for ( int i = 0; i&lt; aliens.size(); i++) {
      if ( aliens.get(i) instanceof Worker) {
        aliens.get(i).dead = true; //marks the old aliens dead so they get removed
      }
    }

    for ( int i = 0; i&lt; 20; i++) {
      aliens.add(new Worker(width/2, height/2, elites.get(j).net));
      j++;
      if (j &gt;= elites.size()) {
        j = 0;
      }
    }
  }
}

ArrayList &lt;Alien&gt; returnFit() {
    ArrayList &lt;Alien&gt; workers; //array to pick the workers out of all aliens
    ArrayList &lt;Alien&gt; elites;
    elites = new ArrayList&lt;Alien&gt;();
    workers = new ArrayList &lt;Alien&gt;();
    for ( int i = 0; i &lt; aliens.size(); i++) {
      Alien m = aliens.get(i);
      if ( m instanceof Worker) {
        workers.add(m);
      }
      Collections.sort(workers, new Sortbyfitness());
    }

    for (int i = workers.size()-1; i &gt;= workers.size()-1 - int(workers.size()* elitesPercent/100); i --) {
      elites.add(workers.get(i));
    }
    return elites;
  }

 //remove the dead aliens
  void clearDead() {
    for (int i = 0; i&lt; aliens.size(); i++) {
      Alien a = aliens.get(i);
      if (a.dead) {
        aliens.remove(a);
        a.removeObserver(tutorial); //important to remove the observers in order to preserve framerate
      }
    }
  }
</code></pre>

<p>I suspect that the agents are not really wiped at the new gen so the program somehow needs to go through all of them and the data gets accumulated somewhere... I am not sure.</p>
]]></description>
   </item>
   <item>
      <title>Frame Rate keeps getting lower</title>
      <link>https://forum.processing.org/two/discussion/27931/frame-rate-keeps-getting-lower</link>
      <pubDate>Mon, 07 May 2018 06:13:02 +0000</pubDate>
      <dc:creator>dehyde</dc:creator>
      <guid isPermaLink="false">27931@/two/discussions</guid>
      <description><![CDATA[<p>Hi</p>

<p>I working on a code running particles to represent refugee data
The code limits the number of particles to keep the frameRate but even after using a steady number of particles, it keeps getting slower with lower frameRate.</p>

<p>I'm really not sure what I can do to make this run faster / smoother. Why does it keep getting slower?</p>

<p>Here's the data folder for the Sketch:
<a href="https://www.dropbox.com/sh/z69phco3tahqklu/AAB8PLMpBQMoFUX5NGSie-5fa?dl=0" target="_blank" rel="nofollow">https://www.dropbox.com/sh/z69phco3tahqklu/AAB8PLMpBQMoFUX5NGSie-5fa?dl=0</a></p>

<pre><code>PImage texture;
PGraphics pg;
PShape worldMap;
import java.util.Map;  
int filterPSystemsNum;

PGraphics sumPG;

// ========== Table Data Stuff 

Table immigrationTable;
Table conflictTable;
Table countryLocations;

int k = 0;
String[] destCountryArray = new String[0];
String[] sourceCountryArray = new String[0];

String destCountry = "";
String prevDestCountry = "";

String sourceCountry;

float mapMultiplyX = 4;
float mapOffsetX = -100;
float mapMultiplyY = 4;
float mapOffsetY = 50;

// ========

int amountSum = 1;

String displayType = "Circular";

int maxParticles = 9000;

ParticleSystem ps;
ParticleSystem ps2;

int n = 0, n2=0;
int emmitMultiplyer = 1;
int emmitFreq = 1;
float particleSpeed = 1;

float locationX = 250;
float locationY = 450;

int[] sourceX = {10, 40, 200, 400, 700};
int[] destX = {300, 600, 300, 600, 600};
int[] amount = {10, 100, 500, 800, 1000};
int highestAmount;

float radius = 300;

float tempLong;
float tempLat;

int yearFilterMin = 1996;
int yearFilterMax = 2016;


ParticleSystem[] PSystems;

HashMap&lt;String, Country&gt; countries = new HashMap&lt;String, Country&gt;();

void setup() {
  size(1200, 800, P2D);
  ((PGraphicsOpenGL)g).textureSampling(3);

  texture = loadImage("paper_texture.jpg");
  //worldMap = loadShape("worldLow.svg");

  //=============== load immigrationTable and create an array of countries


  immigrationTable = loadTable("asylum_seekers_all.csv", "header");
  countryLocations = loadTable("LatLonCountries2.csv", "header");
  conflictTable = loadTable("ged171.csv", "header");

  destCountryArray = (String[]) append(destCountryArray, "Israel");

  sumPG = createGraphics(width, height);

  pg = createGraphics(width, height);
  pg.beginDraw();
  pg.background(177);

  pg.endDraw();
  image(pg, 0, 0);

  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {

      String tempCountryHolder = row.getString("Country / territory of asylum/residence");

      boolean exists = countryExists(tempCountryHolder);
      if (exists==true) {

        continue;
      }

      destCountryArray = (String[]) append(destCountryArray, tempCountryHolder);
    }
  }

  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {

      String tempCountryHolder = row.getString("Origin");

      boolean exists = countryExists(tempCountryHolder);
      if (exists==true) { //println("exists, skipping");
        continue;
      }
      destCountryArray = (String[]) append(destCountryArray, tempCountryHolder);
    }
  }
  destCountryArray = sort(destCountryArray);



  //============================ country hashmaps ======================================

  for (int i = 0; i &lt; destCountryArray.length; i++) {
    String name = destCountryArray[i];




    for (TableRow row : countryLocations.rows()) {


      if (name.equals(row.getString("name"))) {

        tempLong = row.getFloat("longitude");
        tempLat = row.getFloat("latitude");
      }
    }

    countries.put(name, new Country(name, width/2+(tempLong*mapMultiplyX)+mapOffsetX, height/2-(tempLat*mapMultiplyY)+mapOffsetY));

  }

  for (String key : countries.keySet()) {
    Country c = countries.get(key);

  }

  //============================ PSystems =============

  PSystems = new ParticleSystem[immigrationTable.getRowCount()];
  int j = 0;

highestAmount = 291664;

  println(amountSum);
  for (TableRow row : immigrationTable.rows()) {
    if (row.getInt("Year") &lt;= yearFilterMax &amp;&amp; row.getInt("Year") &gt;= yearFilterMin) {
      int tempAmount = row.getInt("decisions_recognized");
      String tempDestCountry = row.getString("Country / territory of asylum/residence");
      String tempSourceCountry = row.getString("Origin");
      int tempYear = row.getInt("Year");

      float sourceEmmiterX = countries.get(tempSourceCountry).x;
      float sourceEmmiterY = countries.get(tempSourceCountry).y;
      float destEmmiterX = countries.get(tempDestCountry).x;
      float destEmitterY = countries.get(tempDestCountry).y;

      PSystems[j] = new ParticleSystem(1, new Vector3D(sourceEmmiterX, sourceEmmiterY, 0), new Vector3D(destEmmiterX, destEmitterY, 0), tempAmount, tempYear);
      println("----");
      filterPSystemsNum++;

      println("tempAmount "+tempAmount);
      println("maxParticles "+maxParticles);
      println("amountSum "+amountSum);
      println("tempAmount*maxParticles "+tempAmount*maxParticles);
      println("tempAmount*(maxParticles/amountSum) "+tempAmount*maxParticles/amountSum); 
      //println("PSystems " + i + " is " +PSystems[i]);
      j++;
    }
  }

  smooth();
}
int currentYear = 2000;
void draw() {

  blendMode(MULTIPLY);
  background(247, 245, 246, 1);
  fill(1, 1, 1, 1);

  tint(255, 1);
  image(pg, 0, 0);

  for (int i = 0; i&lt;filterPSystemsNum; i++) {

    boolean overCountryOrigin = overCountry(int(PSystems[i].origin.x), int(PSystems[i].origin.y), 10);
    boolean overCountryDest = overCountry(int(PSystems[i].dest.x), int(PSystems[i].dest.y), 10);
    boolean isOver = (overCountryOrigin || overCountryDest);
    PSystems[i].run(isOver);
  }


  //  =======

  int allPCount = 0;
  for (int k = 0; k&lt;filterPSystemsNum; k++) {

    Vector3D b=new Vector3D(PSystems[k].origin.x, PSystems[k].origin.y+abs(PSystems[k].origin.x-PSystems[k].dest.x)/2, 0);
    Vector3D c=new Vector3D(PSystems[k].dest.x, PSystems[k].dest.y+abs(PSystems[k].origin.x-PSystems[k].dest.x)/2, 0);


    boolean isTherePLimit = PSystems[k].PLimit != 0;

    if (isTherePLimit){

    boolean isThisAPlayingFrame = frameCount % int(sqrt(highestAmount/PSystems[k].PLimit)) == 0;
    boolean isThisTheRightYear = PSystems[k].year == currentYear;
    boolean areThereAnyMoreParticles = PSystems[k].PCount&lt;PSystems[k].PLimit;

    if (isThisAPlayingFrame &amp;&amp; isThisTheRightYear &amp;&amp; areThereAnyMoreParticles) {
      for(int s = 0; s&lt;emmitMultiplyer; s++){
      PSystems[k].addParticle();
      PSystems[k].PCount++;
      n++;
      }
    }
  }
    }



  // =========================================================== country labels




  for (int i = 0; i&lt;destCountryArray.length; i++) {
    float tempX = countries.get(destCountryArray[i]).x;
    float tempY = countries.get(destCountryArray[i]).y;
    float tempAng = atan((tempY-height/2)/(tempX-width/2));
    float labelMargin;
    translate(tempX, tempY);
    textSize(8);

    rotate(tempAng);
    fill(0);
    if (tempX&lt;width/2) {
      textAlign(RIGHT);
      labelMargin = -7;
    } else {
      textAlign(LEFT);
      labelMargin = 7;
    }

    if (overCountry(int(tempX), int(tempY), 9)==true) {
      fill(50, 100, 250);
      ellipse(0, 0, 5, 5);
      fill(0, 0, 255);
      text(countries.get(destCountryArray[i]).name, labelMargin, 2);
    } else {
      fill (200);
      fill(30, 100-sq(dist(mouseX, mouseY, tempX, tempY)));
      text(countries.get(destCountryArray[i]).name, labelMargin, 2);
    }

    if (countries.get(destCountryArray[i]).name == "Israel") {

      textAlign(RIGHT);
      textSize(10);
      fill(255);
      rotate(-tempAng);
      translate(-tempX, -tempY);
      rect(-6, -8, -textWidth("you are here")-7, 14);

      fill(200, 40, 40);
      text ("you are here", mouseX, mouseY);
      noFill();
      strokeWeight(0.5);
      stroke(255, 0, 0);

      bezier(mouseX, mouseY, (mouseX+tempX)/2+100, mouseY, tempX, (mouseY+tempY)/2, tempX, tempY);
      noStroke();
      translate(tempX, tempY);
      rotate(tempAng);
      ellipse(0, 0, 4, 4);
    }
    rotate(-tempAng);
    translate(-tempX, -tempY);
  }

  fill(0);
  text("Frame rate: "
    + int(frameRate), 10, 20);
  text("Each point: " + int(amountSum/maxParticles) +" people", 10, 30);
  text("number of refugees: " + n*int(amountSum/maxParticles), 10, 40);
  text("number of particles is: " +n, 10, 50);
  text("max particles is: " +maxParticles, 10, 60);
  textSize(80);
  blendMode(BLEND);
  fill(128, 130, 131);
  text(round(float(n)*float(amountSum)/float(maxParticles)), 10, 160);
  textSize(20);
  text("RECOGNIZED REFUGEES (" +yearFilterMin+ " - " + yearFilterMax+")", 10, 180);

  println("n = "+n);
  println("amountSum = "+amountSum);
  println("maxParticles = "+maxParticles);
}




// ==============================//  A simple Particle class  // ===============================================//




class Particle {

  Vector3D loc;
  Vector3D des;
  Vector3D vel;
  Vector3D acc;
  Vector3D locHome, b, c;
  float relativeSpeed;

  float r;
  float timer;

  float t=0.0; 
  float a = random(TWO_PI);
  Particle(Vector3D l, Vector3D m, int accum) {

    acc = new Vector3D(0, 0, 0); //  new Vector3D(random(-0.1, 0.1), random(-0.02, 0), 0);
    loc = l.copy();
    des = m.copy();
    locHome = l.copy();

    float rescale = 0.5;

    locHome.x = locHome.x+ cos(a)*random(0, sqrt(accum)*rescale);
    locHome.y = locHome.y+ sin(a)*random(0, sqrt(accum)*rescale);


    des.x = des.x+ cos(a)*random(0, sqrt(accum)*rescale);
    des.y = des.y+ sin(a)*random(0, sqrt(accum)*rescale);

    relativeSpeed = random(0.1, 0.02);


    r = random(0.9, 3);  // particle radius
    timer = 10000.0;   // particles lifespan


    b=new Vector3D(l.copy().x, l.copy().y+abs(l.copy().x-m.copy().x)/2, 0);
    c=new Vector3D(m.copy().x, m.copy().y+abs(l.copy().x-m.copy().x)/2, 0);

  }

  void run(boolean onMouseOverPSystem) {
    update();
    render(onMouseOverPSystem);
  }



  // Method to update location
  void update() {
    if (t&gt;=1)
      return;

    loc.x = bezierPoint(locHome.x, b.x, c.x, des.x, t);
    loc.y = bezierPoint(locHome.y, b.y, c.y, des.y, t);

    t = lerp(t, 1, particleSpeed*relativeSpeed/2);

  }

  void render(boolean isSelected) {
    ellipseMode(CENTER);
    noStroke();
    blendMode(BLEND);

    if (isSelected == false) {
      fill(128, 129, 129, 150);
    } 
    if (t==lerp(0, 1, particleSpeed*relativeSpeed/2)) {
      pg.beginDraw();
      pg.blendMode(BLEND);
      pg.fill(0, 0, 0);
      pg.noStroke();
      pg.ellipse(loc.x, loc.y, r, r);
      pg.endDraw();
    } else { 
      fill(4*255*t-3*255);
    }
    ellipse(loc.x, loc.y, r, r);

  }

  // Is the particle still useful?
  boolean dead() {
    if (t==1) {
      pg.beginDraw();
      pg.blendMode(BLEND);
      pg.fill(255, 255, 255, 255);
      pg.noStroke();
      pg.ellipse(loc.x, loc.y, r, r);
      pg.endDraw();
      return true;
    } else {
      return false;
    }
  }
}


// ==============================//  A ParticleSystem  // ===============================================// 


// A class to describe a group of Particles
// An ArrayList is used to manage the list of Particles
class ParticleSystem {

  ArrayList particles;    // An arraylist for all the particles
  Vector3D origin;        // An origin point for where particles are birthed
  Vector3D dest;
  int PLimit;
  int PCount;
  int year;

  float ratio = PLimit/highestAmount;

  //ParticleSystem( number of particles / frame, source, destination, frequency);
  ParticleSystem(int num, Vector3D v, Vector3D d, int f, int y) {
    particles = new ArrayList();              // Initialize the arraylist
    origin = v.copy();     // Store the origin point
    dest = d.copy();
    year = y;
    PLimit = f;


    //if (frameCount % (1/f) == 0){
    for (int i = 0; i &lt; num; i++) {
      //  particles.add(new Particle(origin, dest));    // Add "num" amount of particles to the arraylist
    }
    //}
  }

  void run(boolean onMouseOverPSystem) {


    for (int i = particles.size()-1; i &gt;= 0; i--) {
      Particle p = (Particle) particles.get(i);
      p.run(onMouseOverPSystem);
      if (p.dead()) {
        particles.remove(i);
        //PCount--;
        //n--;
      }

    }
  }

  void addParticle() {
    particles.add(new Particle(origin, dest, PCount));
  }



  // A method to test if the particle system still has particles
  boolean dead() {
    if (particles.isEmpty()) {
      return true;
    } else {
      return false;
    }
  }
}

//=================================================== Class Country

class Country {
  String name;
  float x, y, lon, lat, migrationIndex, incoming, outgoing;
  // more things here?

  Country(String name, float x, float y) {
    this.name = name;
    this.x = x;
    this.y = y;
  }
}

// ================================================ Simple Vector3D Class


public class Vector3D {

  public float x;
  public float y;
  public float z;

  Vector3D(float x_, float y_, float z_) {
    x = x_; 
    y = y_; 
    z = z_;
  }

  Vector3D(float x_, float y_) {
    x = x_; 
    y = y_; 
    z = 0f;
  }

  Vector3D() {
    x = 0f; 
    y = 0f; 
    z = 0f;
  }

  void setX(float x_) {
    x = x_;
  }

  void setY(float y_) {
    y = y_;
  }

  void setZ(float z_) {
    z = z_;
  }

  void setXY(float x_, float y_) {
    x = x_;
    y = y_;
  }

  void setXYZ(float x_, float y_, float z_) {
    x = x_;
    y = y_;
    z = z_;
  }

  void setXYZ(Vector3D v) {
    x = v.x;
    y = v.y;
    z = v.z;
  }

  public float magnitude() {
    return (float) Math.sqrt(x*x + y*y + z*z);
  }

  public Vector3D copy() {
    return new Vector3D(x, y, z);
  }

  public Vector3D copy(Vector3D v) {
    return new Vector3D(v.x, v.y, v.z);
  }

  public void add(Vector3D v) {
    x += v.x;
    y += v.y;
    z += v.z;
  }

  public void sub(Vector3D v) {
    x -= v.x;
    y -= v.y;
    z -= v.z;
  }

  public void mult(float n) {
    x *= n;
    y *= n;
    z *= n;
  }

  public void div(float n) {
    x /= n;
    y /= n;
    z /= n;
  }

  public void normalize() {
    float m = magnitude();
    if (m &gt; 0) {
      div(m);
    }
  }

  public void limit(float max) {
    if (magnitude() &gt; max) {
      normalize();
      mult(max);
    }
  }

  public float heading2D() {
    float angle = (float) Math.atan2(-y, x);
    return -1*angle;
  }

  public Vector3D add(Vector3D v1, Vector3D v2) {
    Vector3D v = new Vector3D(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
    return v;
  }

  public Vector3D sub(Vector3D v1, Vector3D v2) {
    Vector3D v = new Vector3D(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
    return v;
  }

  public Vector3D div(Vector3D v1, float n) {
    Vector3D v = new Vector3D(v1.x/n, v1.y/n, v1.z/n);
    return v;
  }

  public Vector3D mult(Vector3D v1, float n) {
    Vector3D v = new Vector3D(v1.x*n, v1.y*n, v1.z*n);
    return v;
  }

  public float distance (Vector3D v1, Vector3D v2) {
    float dx = v1.x - v2.x;
    float dy = v1.y - v2.y;
    float dz = v1.z - v2.z;
    return (float) Math.sqrt(dx*dx + dy*dy + dz*dz);
  }
}

boolean countryExists(String tempCountryHolder) {

  for (int i = 0; i &lt; destCountryArray.length; i++) {

    if (tempCountryHolder.equals(destCountryArray[i]) == true) {

      return true; // it exists
    } //if
  } //for
  return false ; // not found
}//func


//============================================= onMouseOver Bolean Class


boolean overParticle(int x, int y, int diameter) {
  float disX = x - mouseX;
  float disY = y - mouseY;
  if (sqrt(sq(disX) + sq(disY)) &lt; diameter/2 ) {
    return true;
  } else {
    return false;
  }
}

boolean overCountry(int x, int y, int diameter) {
  float disX = x - mouseX;
  float disY = y - mouseY;
  if (sqrt(sq(disX) + sq(disY)) &lt; diameter/2 ) {
    return true;
  } else {
    return false;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Bullet runs into issue when collided with more then one enemy</title>
      <link>https://forum.processing.org/two/discussion/27928/bullet-runs-into-issue-when-collided-with-more-then-one-enemy</link>
      <pubDate>Mon, 07 May 2018 00:59:21 +0000</pubDate>
      <dc:creator>ctrembla</dc:creator>
      <guid isPermaLink="false">27928@/two/discussions</guid>
      <description><![CDATA[<p>Hey, I'm making a space invaders game &amp; I made a bunch of different kind of bullets the player can use, but when a bullet collides with 2 enemies it gives me a bullet remove error.
<code>for (int i = Bullet.size()-1; i &gt;= 0; i--)
{ bullet bu = Bullet.get(i); 
bu.show(); 
bu.move(); 
for (int j = Enemy.size()-1; j &gt;= 0; j--)
{ enemy en = Enemy.get(j); 
float d = dist(bu.x,bu.y,en.x,en.y); 
if (d &lt; bu.r + en.r){ 
Bullet.remove(i); 
en.life -= 1; } } }</code></p>

<p>anyone know a way to fix it so my bullet ca hit 2 enemies without an error. I think the trouble is that both enemies it collided with are trying to remove it at the same time.</p>
]]></description>
   </item>
   <item>
      <title>Index size Problem</title>
      <link>https://forum.processing.org/two/discussion/27872/index-size-problem</link>
      <pubDate>Sat, 28 Apr 2018 20:20:38 +0000</pubDate>
      <dc:creator>Drewsg</dc:creator>
      <guid isPermaLink="false">27872@/two/discussions</guid>
      <description><![CDATA[<p>Hi, this is a problem that I have been having for a while. My program works fine until you fire too many bullets and the array gets bogged down, the thing is, I don't know why it keeps breaking at its limit.</p>

<pre><code>//April 28, 2018

float randomside = 0.0;

ArrayList&lt;Integer&gt; bulletup = new ArrayList&lt;Integer&gt;();
ArrayList&lt;Integer&gt; dotposition = new ArrayList&lt;Integer&gt;();

ArrayList&lt;Integer&gt; balloonX = new ArrayList&lt;Integer&gt;();
ArrayList&lt;Integer&gt; balloonY = new ArrayList&lt;Integer&gt;();

int moveup = 60;
float fastdot = mouseX;
float dotcoordiant = -50;
int lastTimeCheck;
int timeIntervalFlag = 6500;
int timeIntervalFlag2 = 30;

int drawCount = 0;

void setup() {
  // set size of display

  size (500, 720);
  background (256, 256, 256);
  strokeWeight(10);
  frameRate(60);
  lastTimeCheck = millis();
}


void mousePressed(){
  println("the mouse was pressed at ",mouseX);
  dotposition.add(mouseX);
  bulletup.add(650);
}

int distance2(int X1, int Y1, int X2, int Y2){
  int a = X2 - X1;
  int b = Y2 - Y1;
  return(a * a + b * b);
}

boolean isFirstOffTop(ArrayList&lt;Integer&gt; myBullets){
  if (myBullets.size() == 0){
    return(false);
  }
  if (myBullets.get(0) &gt; 0){
    return(false);
  }
  return(true);
}

boolean isFirstOffBottom(ArrayList&lt;Integer&gt; myBullets){
  if (myBullets.size() == 0){
    return(false);
  }
  if (myBullets.get(0) &lt; 780){
    return(false);
  }
  return(true);
}

void draw() {
  background (256, 256, 256);
  randomside = random(450);
  stroke(0, 0, 256);
  point(mouseX, 650);

  //bulletcode

  // remove front bullets that have reached the top
  while (isFirstOffTop(bulletup)){
    bulletup.remove(0);
    dotposition.remove(0);
  }

  // draw the moving bullets
  for (int bi = 0; bi &lt; dotposition.size(); bi++) {
      point(dotposition.get(bi), bulletup.get(bi));
      bulletup.set(bi, bulletup.get(bi) - 6);
  }


  if ( millis() &gt; lastTimeCheck + timeIntervalFlag ) {
    lastTimeCheck = millis();
    moveup = 60;
    println(lastTimeCheck);
  }
  /*if ( millis() &gt; lastTimeCheck + timeIntervalFlag2 ) {
   lastTimeCheck = millis();
   bulletup = bulletup;
   println(lastTimeCheck);

   }
   */

   // make another arraylist of "ballons",
   // on each draw create one new balloon at the top of the screen
   // at random X positions
   // slide every balloon down 10 pixels/frame
  drawCount += 1;
  if (drawCount &gt; 1){
    // generate one more balloon at top of screen
    balloonX.add(int(random(500)));
    balloonY.add(0);
    drawCount = 0;
  }

  // remove balloons that have reached the bottom
  while (isFirstOffBottom(balloonY)){
    balloonX.remove(0);
    balloonY.remove(0);
  }

  // draw the falling balloons
  stroke(256, 0, 0);
  for (int bi = 0; bi &lt; balloonX.size(); bi++) {
      point(balloonX.get(bi), balloonY.get(bi));
      balloonY.set(bi, balloonY.get(bi) + 5);

  }
  println("ballon size = ", balloonX.size());
  // pop balloons that have been hit
  int dist = 10;
  int dist2 = dist * dist;
  // loop backwards so I can delete through indexed loop
  for (int bi = balloonX.size() - 1; bi &gt;= 0; bi--) {
      for (int si = 0; si &lt; dotposition.size(); si++){
        println("ballon size = ", balloonX.size());
        if (distance2(dotposition.get(si), bulletup.get(si),
            balloonX.get(bi), balloonY.get(bi)) &lt;= dist2) {
               balloonX.remove(bi); 
               balloonY.remove(bi); 
            }
      }
  }
  // Kill balloons that have reached the bottom
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to delete or remove an object from an ArrayList?</title>
      <link>https://forum.processing.org/two/discussion/27683/how-to-delete-or-remove-an-object-from-an-arraylist</link>
      <pubDate>Tue, 03 Apr 2018 17:23:45 +0000</pubDate>
      <dc:creator>mHoneycomb</dc:creator>
      <guid isPermaLink="false">27683@/two/discussions</guid>
      <description><![CDATA[<p>I have a sketch that creates a new object and adds it into an ArrayList every xxx number of seconds using a timer.
I would like each object created to have a life span, and then be deleted when it's life span finishes.</p>
]]></description>
   </item>
   <item>
      <title>Problems with Buffer (EyeTracker)</title>
      <link>https://forum.processing.org/two/discussion/26453/problems-with-buffer-eyetracker</link>
      <pubDate>Tue, 20 Feb 2018 14:54:56 +0000</pubDate>
      <dc:creator>eyetrackeruntref</dc:creator>
      <guid isPermaLink="false">26453@/two/discussions</guid>
      <description><![CDATA[<p>I'm receiving data from Matlab (1000fps) of a subject looking a picture using EyeTracker Hardware. [both in different computers].</p>

<p>Connection is OK, UDP is fine, OSC is working thanks to oscP5.</p>

<p>With the data, I draw circles ( that are designed by X and Y axis from EyeTracker device ) in a canvas.</p>

<p>Now the problem is that I don't know how to build a proper buffer to receive all this massive information, and then, after few milliseconds erase it. Because I want to see in my canvas, the eyes moving on real time drawing circles, but i just want to see 1 circle, not all of them, eventhough i don't need to save all this information.</p>

<p>If you don't understand something, please ask me, and I'll try to explain you better:</p>

<p>I have this code, feel free to ask and say whatever you want :</p>

<pre><code>/**
 * oscP5parsing by andreas schlegel
 * example shows how to parse incoming osc messages "by hand".
 * it is recommended to take a look at oscP5plug for an
 * alternative and more convenient way to parse messages.
 * oscP5 website at <a href="http://www.sojamo.de/oscP5" target="_blank" rel="nofollow">http://www.sojamo.de/oscP5</a>
 */
import java.util.*;

import oscP5.*;
import netP5.*;

OscP5 oscP5;
NetAddress myRemoteLocation;

ArrayList &lt;Posiciones&gt; buffer  = new ArrayList&lt;Posiciones&gt;();

//Iterator &lt;Posiciones&gt; itr = new ArrayList&lt;Posiciones&gt;();


long tiempoX = 1000;
long tiempoActual = millis(); 

float x1, y1, x2, y2;
float diamt = 20;

float ancho = 400;
float alto = 400;

void setup() {
  size(400, 400); 
  smooth();
  noStroke();
  /* start oscP5, listening for incoming messages at port 8002 */
  oscP5 = new OscP5(this, 8002); //Pasar este puerto al experimento de MatLab

  /* myRemoteLocation is a NetAddress. a NetAddress takes 2 parameters,
   * an ip address and a port number. myRemoteLocation is used as parameter in
   * oscP5.send() when sending osc packets to another computer, device, 
   * application. usage see below. for testing purposes the listening port
   * and the port of the remote location address are the same, hence you will
   * send messages back to this sketch.
   */
  //myRemoteLocation = new NetAddress("127.0.0.1", 4002);
}

void draw() {

  escupirData();
  dibujarCirculos();
}

void oscEvent(OscMessage theOscMessage) {
  /* check if theOscMessage has the address pattern we are looking for. */

  if (theOscMessage.checkAddrPattern("/test")==true) {
    /* check if the typetag is the right one. */
    //println(theOscMessage);
    if (theOscMessage.checkTypetag("s")) {
      /* parse theOscMessage and extract the values from the osc message arguments. */
      String stringValue = theOscMessage.get(0).stringValue();
      println(" values: " + stringValue);

      int[] datos = int(split(stringValue, "-")); //divide los datos y los guarda temporalmente //  divide data and save temporarily
      Posiciones crearPosiciones = new Posiciones(); //creo un objeto para guardar la data // creating an object to save the data
      crearPosiciones.x1 = datos[0]; //guardo la data // saving data
      crearPosiciones.y1 = datos[1];
      crearPosiciones.x2 = datos[2];
      crearPosiciones.y2 = datos[3];
      buffer.add(crearPosiciones); //agrego un elemento al arrayList/buffer // adding an element to arrayList/buffer

      return;
    }
  }
}

void escupirData() {

  long currentMillis = millis();

  if (millis() - tiempoActual &gt;= tiempoX ) {
    //Pixel newPixel = pixeles.get(i); 

    if (buffer.size() &gt; 0) { //fijarse si el buffer tiene elementos // look if the buffer has elements
      Posiciones posicionActual = buffer.get(0); //creo un objeto para guardar el primer objeto del buffer // creating an object to save the first object of the buffer

      x1 = posicionActual.x1; //guardo la data para usar // saving the data to use
      y1 = posicionActual.y1;
      x2 = posicionActual.x2;
      y2 = posicionActual.y2;


      posicionActual.borrar = true;//si ya lo dibujé levanto el flag para borrarlo // if it is drawn, clear

      println(" borrado: " + posicionActual.borrar);

      tiempoActual = millis();
    }
  }

  //crear un iterator, que si ya dibujó la posición lo borre por el flag // creating an iterator

  //creo un iterator para podes remover lugares del ArrayList // creating an iterator to remove spots of ArrayList
  Iterator itr = buffer.iterator();
  // itr = buffer.iterator();
  while (itr.hasNext ()) {
    Posiciones posicionActual = (Posiciones)itr.next();
    if (posicionActual.borrar) {
      itr.remove(); //remuevo la frase que ya no se ve // removing the phrase that is not visible
      println("borré 1, quedan " + buffer.size() + " posiciones");
    }
  }
}

void dibujarCirculos() {

  x1 = map(x1, 0, ancho, 0, width); 
  y1 = map(y1, 0, ancho, 0, height);
  x2 = map(x2, 0, ancho, 0, width); 
  y2 = map(y2, 0, ancho, 0, height); 

  fill(255, 0, 0);
  ellipse(x1, y1, diamt, diamt);
  fill(0, 0, 255);
  ellipse(x2, y2, diamt, diamt);
}


AND THIS CLASS :

class Posiciones {
  int x1, y1, x2, y2;
  boolean borrar = false;


  Posiciones() {
  }

  void vacio() {
  }

}
</code></pre>
]]></description>
   </item>
   <item>
      <title>(Newbie) IndexOutOfBoundsException: Index: 0, Size: 0 - Trying to remove objects</title>
      <link>https://forum.processing.org/two/discussion/26589/newbie-indexoutofboundsexception-index-0-size-0-trying-to-remove-objects</link>
      <pubDate>Thu, 01 Mar 2018 04:31:56 +0000</pubDate>
      <dc:creator>verycoolveryswag</dc:creator>
      <guid isPermaLink="false">26589@/two/discussions</guid>
      <description><![CDATA[<p>Hey,
I'm trying to remove objects when home == false in order to clear the canvas to change the scene.
Read somewhere that you had to do it with an ArrayList but I'm not confident at all with them and I'm probably doing something really dumb.</p>

<p>Also I'm not sure if this is the best way to change scenes.</p>

<p>Getting error: IndexOutOfBoundsException: Index: 0, Size: 0</p>

<p>Thanks heaps in advance.</p>

<pre><code>int hunger;
int hungerIncrease = 1;
int happiness;
int happyIncrease = 1;

int jingling;

boolean home;
boolean shop;

Status status;
Button button;

ArrayList&lt;Button&gt; buttonL = new ArrayList&lt;Button&gt;(0);
ArrayList&lt;Status&gt; statusL = new ArrayList&lt;Status&gt;(0);

void setup() {

  //window
  size(320, 320);

  //loading
  status = new Status();
  button = new Button();

  buttonL.add(new Button());
  statusL.add(new Status());

  //variables
  hunger = 5;
  happiness = 5;
  jingling = 50;
  home = true;
  shop = false;

}

void draw() {

  if (home == true) {
    Button bpart = buttonL.get(0);
    bpart.show();

    Status spart = statusL.get(0);
    spart.show();
  } else {
    buttonL.remove(0);
    statusL.remove(0);
  }

  ////limits
  if (hunger &gt; 10) {
    hunger = 10;
  }

  if (happiness &gt; 10) {
    happiness = 10;
  }
}

void mouseClicked() {
  if (home == true) {
    button.clicked();
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>best pattern for collections with remove-during-iteration?</title>
      <link>https://forum.processing.org/two/discussion/26133/best-pattern-for-collections-with-remove-during-iteration</link>
      <pubDate>Fri, 26 Jan 2018 18:15:20 +0000</pubDate>
      <dc:creator>kirkjerk</dc:creator>
      <guid isPermaLink="false">26133@/two/discussions</guid>
      <description><![CDATA[<p>Hi there!</p>

<p>I'm updating some very old Processing cold - <a href="https://toys.alienbill.com/" target="_blank" rel="nofollow">https://toys.alienbill.com/</a> - to run in browsers.
Basically that means opening it in Processing 2, getting it to work there as Java, then switching to Processing.js
(I haven't looked to make sure that Processing 3 still doesn't know Processing.js, but that's how it was a while back)</p>

<p>My biggest problem is with collections.</p>

<p>My old favorite was HashSet, which is no longer supported - but it made sense to me to say "I have a bunch of stuff I want to draw, I don't care what order". And then I would</p>

<pre><code>HashSet&lt;Thing&gt; things = new HashSet&lt;Thing&gt;();
// ... add some things
// now loop:
Iterator&lt;Thing&gt; i = things.iterator();
while(i.hasNext){
   Thing t = i.next();
   t.move();
   if(t.isDead()){
        i.remove();
  }
}
</code></pre>

<p>So, the syntax was clunky, but the procedure was a little cleaner than my current practice of having an ArrayList just to store the things I want to remove, then removing them all at once...</p>

<pre><code>ArrayList&lt;Thing&gt; things = new ArrayList&lt;Thing&gt;();
//...add some things
//now loop:
ArrayList&lt;Thing&gt; thingsToRemove = new ArrayList&lt;Thing&gt;();
for(Thing t : things){
  t.move();
  if(t.isDead()){
     thingsToRemove.add(t);
  }
}
things.removeAll(thingsToRemove);
</code></pre>

<p>(this because ArrayList's for() explodes if you try and remove while iterating over it)</p>

<p>So is there a cleaner way to remove something from a collection as you're iterating over that same collection?
(In js, you can splice and what not if you iterate BACKWARDS from the end of an array... clearly a little hacky)</p>
]]></description>
   </item>
   <item>
      <title>how to do inetarcction</title>
      <link>https://forum.processing.org/two/discussion/25170/how-to-do-inetarcction</link>
      <pubDate>Thu, 23 Nov 2017 19:13:42 +0000</pubDate>
      <dc:creator>ppp</dc:creator>
      <guid isPermaLink="false">25170@/two/discussions</guid>
      <description><![CDATA[<pre><code>  ArrayList bales;
Bala bala1;

ArrayList soldats;
Soldat soldat1;
boolean matar= false;

void setup() {
size(600, 500);
stroke(255);
fill(255, 255, 255);
bales = new ArrayList();
bala1 = new Bala();

soldats= new ArrayList();
soldat1 = new Soldat();

bales.add( bala1 );
soldats.add (soldat1);
}

void draw() {
background(51);
line(300, 500, mouseX, 2 * mouseY);
strokeWeight(mouseY/10);

for ( int i = 0; i &lt; bales.size(); i++) {
bala1 = (Bala)bales.get(i);
bala1.balesmoviment();

for ( int i = 0; i &lt; bales.size(); i++) {
soldat1 = (Soldat)soldats.get(i);
soldat1.soldatsmoviment();
}
}

if (balapx = soldatpx) {
matar=true; // matar is kill, when bala collision rectangle (soldat=soldier) soldier die (dissapear)


class Bala {
float balapx, balapy;
float balavx, balavy;
Bala() {//creamos una bala
balapx = width/2.0;
balapy = height;
balavx = map(mouseX, 0, width, -10, 10);
balavy = -10;
}
void balesmoviment() {
balapx += balavx;
balapy += balavy;
ellipse( balapx, balapy, 10, 10);
}
//================================================================
class Soldat { // Here the problem, how to make rectangles that move and avance in the map
float soldatpx, soldatpy;
float i;
Soldat() {//creamos unsoldat
soldatpx = width+i;
soldatpy = 0;
}
void soldatsmoviment() {
soldatpx +=i;

rect( soldatpx, balapy, 10, 20);
}
}
}
}


void mousePressed() {
if ( bales.size() &gt; 9 ) bales.remove(0);
bales.add( new Bala() );
}
</code></pre>

<p>Don't do pro things</p>
]]></description>
   </item>
   <item>
      <title>Changing colour of shapes over time</title>
      <link>https://forum.processing.org/two/discussion/25166/changing-colour-of-shapes-over-time</link>
      <pubDate>Thu, 23 Nov 2017 12:54:53 +0000</pubDate>
      <dc:creator>maltwhisker</dc:creator>
      <guid isPermaLink="false">25166@/two/discussions</guid>
      <description><![CDATA[<p>Hi everyone,</p>

<p>Now I'm very rusty with processing so I'm 100% sure I'm making some dumb mistakes here.</p>

<p>I'm trying to make the ellipses in this sketch change colour as they become older but I can't figure it out for the life of me!</p>

<p>Thanks in advance for any help/suggestions :)</p>

<p>See code here:</p>

<pre><code>import ddf.minim.*;

Minim minim;
AudioInput in;
 float volume = 0;
float volumeF = 0;

   int maxParticles=1000; // max number of particles. real particles count depends on ppf and its lifetime
int addPPF=2;         // number of particles per frame added
ArrayList particles;

void setup(){
  size(900,900, P3D);
  frameRate(30);
  smooth();
  background(0);
  noStroke();
     minim = new Minim(this);
  minim.debugOn();

  // get a line in from Minim, default bit depth is 16
  in = minim.getLineIn(Minim.MONO, 512);


  particles = new ArrayList();
}

void draw(){
  background(0); // overpaint circles the frame before
  //  for(int i = 0; i &lt; 1; i++)
  //{
     volumeF = in.right.level()*1000;
  volume = 0.8*volume + 0.2*volumeF;
  if(particles.size()&lt;maxParticles){
    // add particle(s)
    for(int k=1; k&lt;= volume; k++){
      particles.add(new Particles());
    }
  }
  //}

  // run trought all Balls and make some action
  for(int j=0; j&lt;particles.size(); j++){
    Particles particle = (Particles)particles.get(j);
    // if particle still alive
    if( particle.alive() ){
      // update x/y positions
      particle.position();
      // now draw as cirle
      if( particle.lt &lt; 200 ) fill(20, 20, 20, particle.lt);
      else if(particle.lt &gt;= 200) fill(50, 50, 50, particle.lt);
      else if(particle.lt &gt;= 300) fill(100, 100, 100, particle.lt);
      else if(particle.lt &gt;= 400) fill(150, 150, 150, particle.lt);
      else if(particle.lt &gt;= 500) fill(200, 200, 200, particle.lt);
      else if(particle.lt &gt;= 600) fill(250, 250, 250, particle.lt);
      //stroke(random(100));
      ellipse(particle.x, particle.y, particle.r, particle.r);

  }else{
      // if lifetime is running out, delete
      particles.remove(j);
    }
  }
}


  void stop()
{
  // always close Minim audio classes when you are done with them
  in.close();
  minim.stop();

  super.stop();
}

public class Particles {
  float r, x, y, _x, _y, dx=0, dy=0, lt;

  // init start-values
  public Particles() {
    // start position center
    x=width/2;
    y=height/2;
    // now random values to make it non-linear
    lt=random(5,2000);       // lifetime in frames
    r=random(1, 4);        // circle Radius
    _x=random(-0.001, 0.001);    // stepwidth in x-pos (left, right)
    _y=random(-0.001, 0.001);    // stepwidth in y-pos (up, down)
  }

  public void position() {
    // stepwidth increases, circlespeed is exponential
    dx+=_x;
    dy+=_y;
    x+=dx;
    y+=dy;
  }

  public boolean alive(){
     if(lt&lt;=0){ return false; }else{ lt--; return true; }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Unique random number for elements in array</title>
      <link>https://forum.processing.org/two/discussion/7696/unique-random-number-for-elements-in-array</link>
      <pubDate>Sun, 19 Oct 2014 14:58:55 +0000</pubDate>
      <dc:creator>tutoki</dc:creator>
      <guid isPermaLink="false">7696@/two/discussions</guid>
      <description><![CDATA[<p>Unique random number for elements in array</p>

<p>I have to create an array of numbers (five element) that have to be unique</p>

<pre><code>int[] numbers = new int[5];
for (int h = 0; h &lt;= 4; h++)
{
 // how to check this random number is unique
    numbers[h] = (int)random(0, 7);
}
printArray(numbers);
</code></pre>

<p>Any clue ?
Thank in advance
SALUD...</p>
]]></description>
   </item>
   <item>
      <title>arrays + midi msj</title>
      <link>https://forum.processing.org/two/discussion/24826/arrays-midi-msj</link>
      <pubDate>Tue, 31 Oct 2017 22:04:21 +0000</pubDate>
      <dc:creator>vjjv</dc:creator>
      <guid isPermaLink="false">24826@/two/discussions</guid>
      <description><![CDATA[<p>Hi! i cant resolve a problem here. 
Im trying to do a music visualizer. The idea is very simple; when i press a Key in my midiController add a new Particle, and when i release, delete that Particle. but when i release a key, all particles are delete. What i was looking for is that only delete the Particle what was correspond that key that i was release. 
here the code:</p>

<pre><code>import themidibus.*;
MidiBus myBus;

int pitchs;
float cc [] =new float [256];
boolean note;
ArrayList&lt;Particle&gt;part;

void setup () {

  fullScreen();
  background(0);
  note = true;
  myBus= new MidiBus(this, "visuals", "visuals");
  part = new ArrayList &lt;Particle&gt;();
}

void draw() {

  background(0);

  for (int i = part.size()-1; i&gt;= 0; i--) {
    Particle p = part.get(i);
    p.update();
    p.display();

    if(p.isDead()){
    part.remove(i);
    }
  }
}

void noteOff(int channel, int pitch, int velocity) {

  println();
  println("Note Off:");
  println("--------");
  println("Channel:"+channel);
  println("Pitch:"+pitch);
  println("Velocity:"+velocity);
  note=false;
  pitchs = pitch;
}

void noteOn(int channel, int pitch, int velocity) {

  println();
  println("Note On:");
  println("--------");
  println("Channel:"+channel);
  println("Pitch:"+pitch);
  println("Velocity:"+velocity);
  pitchs= pitch;
  note = true;
  part.add(new Particle(random(width), random(height), pitchs, note));
}



void controllerChange(int channel, int number, int value) {
  // Receive a controllerChange
  println();
  println("Controller Change:");
  println("--------");
  println("Channel:"+channel);
  println("Number:"+number);
  println("Value:"+value);

  cc[number]=map(value, 0, 127, 0, 1);
}

class Particle {

  PVector pos, vel, acel;
  float pitch;
  float life;
  boolean notes;

  Particle (float x, float y, float pitchs) {
    pos = new PVector(x, y);
    vel = new PVector(random(-1, 1), random(-1, 1));
    acel = new PVector(0, 0);
    pitch = pitchs;
    life = 255;

  }

  void update() {
    pos.add(vel);
    vel.add(acel);
    vel.limit(1);
    life-=1;
  }

  void display() {
    float r = map(pitchs, 0, 127, 0, 200);
    fill(255);
    noStroke();
    ellipse(pos.x, pos.y, r, r);
  }

  boolean isDead() {

    if (note==false || life &lt; 0) {
      return true;
    } else {
      return false;
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Need help for removing an ellipse</title>
      <link>https://forum.processing.org/two/discussion/24766/need-help-for-removing-an-ellipse</link>
      <pubDate>Fri, 27 Oct 2017 14:45:39 +0000</pubDate>
      <dc:creator>akfang</dc:creator>
      <guid isPermaLink="false">24766@/two/discussions</guid>
      <description><![CDATA[<p>hi,
I have to do a project for school, and i encountered a problem i can't solve.
My project is to do a "<a rel="nofollow" href="http://www.koalastothemax.com">koalastothemax.com</a>" like.</p>

<p>There is my code</p>

<pre><code>circle m1;
PImage img;


ArrayList&lt;circle&gt; table = new ArrayList&lt;circle&gt;();


void setup(){
  size(500,500);
  m1 = new circle(250,250,width-50, height-50);
  table.add(m1);

  background(255);

  img = loadImage("pickashoe.jpg");
}

void draw(){

  color c = get(m1.posX,m1.posY);
  fill (c);
  noStroke();

  for (int i = 0; i &lt; table.size(); i++) {
  circle pastille = table.get(i);
  pastille.dessiner();
  pastille.clique();
  }
}

class circle{

  int posX;
  int posY;
  int rX;
  int rY;
  boolean clicked=false;
  int i = 0;
  circle pastille=this;

  circle( int tmp1, int tmp2, int tmp3, int tmp4){
    posX = tmp1 ;
    posY = tmp2 ;
    rX = tmp3 ;
    rY = tmp4;
  }

  void dessiner(){

    fill(img.get(posX,posY));

    if(clicked==false){
    noStroke();
    ellipseMode(CENTER);
    ellipse(posX,posY, rX, rY);
    }
  }

  void clique(){

    if (mousePressed==true &amp;&amp; mouseX &gt; posX-rX/2 &amp;&amp; mouseX &lt; posX+rX/2 &amp;&amp; mouseY &gt; posY-rY/2 &amp;&amp; mouseY &lt; posY+rY/2){
      clicked=true; 
    }

    if(clicked==true){
      if(rX &gt; 7 &amp;&amp; rY &gt; 7){ 
        circle pastille2 = new circle(posX-rX/4,posY-rY/4,rX/2, rY/2 );
        table.add(pastille2);

        circle pastille3 = new circle(posX-rX/4,posY+rY/4,rX/2, rY/2 );
        table.add(pastille3);  

        circle pastille4 = new circle(posX+rX/4,posY-rY/4,rX/2, rY/2 );
        table.add(pastille4);

        circle pastille5 = new circle(posX+rX/4,posY+rY/4,rX/2, rY/2 );
        table.add(pastille5);

        table.remove(this);
        pastille= null;
      }
    }
}
</code></pre>

<p>So, my problem is when my ellipses divide theirselves into 4 littles ellipses, the original wont disapear.</p>

<p>First of all I tried a "table.remove(this)" to remove ellipse which divides herself;
(this allow the program to not having freezes, so it's useful and it's working somehow. But not as I want.)</p>

<p>I also tried to turn "this" to null; but it seems useless.
I tried many others things but no one works.</p>

<p>Well if someone can help me, it would be awesome and very appreciated ! :)
(sorry if my english isn't that good :/ hope it's understandable)</p>
]]></description>
   </item>
   <item>
      <title>Python object iteration problem</title>
      <link>https://forum.processing.org/two/discussion/24279/python-object-iteration-problem</link>
      <pubDate>Wed, 27 Sep 2017 12:33:57 +0000</pubDate>
      <dc:creator>xwxga</dc:creator>
      <guid isPermaLink="false">24279@/two/discussions</guid>
      <description><![CDATA[<p>Hi, I am using python-mode to follow Particle System on NOC, the iterator issue couldn't be solved by my own. Apparently, in the particle system object, every operation were made on single object Particle. I've attached my code, please help.</p>

<p>`````</p>

<pre><code>def setup():
    global ps
    size(800,300)
    randomSeed(1)
    ps = ParticleSystem(PVector(width/2,height/3))
    background(255)
    smooth()
    frameRate(60)


def draw():
    global ps
    background(255)
    ps.addParticle()
    ps.run()
</code></pre>

<p><code>class Particle(object):</code></p>

<pre><code>    def __init__(self,location):
        self.location  = location 
        self.vel = PVector(random(-1,1),random(-1,1))
        self.acc = PVector (0,0.05)
        self.lifespan = 255

    def run(self):
        self.update()
        self.display()

    def update(self):
        self.location.add(self.vel)
        self.vel.add(self.acc)
        self.lifespan -= 2.0

    def display(self):
        stroke(0,self.lifespan)
        strokeWeight(2)
        fill(255,255,0,self.lifespan)
        ellipse(self.location.x,self.location.y,12,12)

    def isDead(self):
        if (self.lifespan&lt;=0.0):            
            return True
        else:
            return False



from Particle import *

class ParticleSystem(object):

    def __init__(self,origin):
        self.origin=origin 
        self.particles = [Particle(self.origin) for i in range(10)]  ###****where i think the problem is ****

    def run(self):    
        for particle in self.particles:
            particle.run()                            ###****where i think the problem is, every opreation is made on single object****
            if particle.isDead() == True:
                self.particles.remove(particle)
        # for  i in range(len(self.particles)):
        #     print i,"---",self.particles[i].location

    def addParticle(self):
        p = Particle(self.origin)
        self.particles.append(p)  
</code></pre>

<p>`````</p>
]]></description>
   </item>
   <item>
      <title>How to reference something else with the same class</title>
      <link>https://forum.processing.org/two/discussion/23967/how-to-reference-something-else-with-the-same-class</link>
      <pubDate>Tue, 29 Aug 2017 22:10:27 +0000</pubDate>
      <dc:creator>Deiplz</dc:creator>
      <guid isPermaLink="false">23967@/two/discussions</guid>
      <description><![CDATA[<p>I'm making a game where the enemies attack each other, how do I do that?</p>

<pre><code>ArrayList &lt;enemy&gt; enemies = new ArrayList &lt;enemy&gt; ();
ArrayList &lt;wall&gt; walls = new ArrayList &lt;wall&gt; ();
void setup() {
  size(1000, 700);
  frameRate(60);

}
void draw() {
  background(0);
      enemy e = new enemy();
  if (frameCount %100==0) {


    enemies.add(e);
  }
  for (int i = enemies.size() - 1; i &gt;= 0; i-=1) {
    enemy zz = enemies.get(i);
    if (zz.isalive==false) {
      enemies.remove(i);
    } else {
      zz.display();
      zz.move(e);
    }
  }
}
//================================================================
class enemy {
  boolean isalive = true, detected = false;
  float x  = -10000, y = -10000, size = 20,lock = -1,identity = random(99999);
  String names = "hi";
  enemy() {
    x  = random(width);
    y  = random(height);
  }
  void display() {
    fill(200, 0, 0);
    rect(x, y, size, size);
  }
  void move(enemy other) {
    if (dist(other.x, other.y, x, y)&lt;other.size + size + 100) {
      detected = true;
      lock = other.identity;
    }
    if (other.isalive ==false) {
      detected = false;
      lock = -1;
    }
    if (detected &amp;&amp; other.identity == lock) {
      if (x &gt; other.x) {
        x -= 5;
      }
      if (x &lt; other.x) {
        x += 5;
      }
      if (y &gt; other.y) {
        y -= 5;
      }
      if (y &lt; other.y) {
        y += 5;
      }
    }
    if (dist(x,y,other.x,other.y)&lt;20){
      other.isalive = true;
    }
  }
}
//==============================================================
class me {
}
//============================================================
class wall {
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>making particle system more efficient (in particular when they are deleted)</title>
      <link>https://forum.processing.org/two/discussion/23257/making-particle-system-more-efficient-in-particular-when-they-are-deleted</link>
      <pubDate>Thu, 29 Jun 2017 13:37:40 +0000</pubDate>
      <dc:creator>secondsky</dc:creator>
      <guid isPermaLink="false">23257@/two/discussions</guid>
      <description><![CDATA[<p>Hi all, i'm trying to do a particle system where basically i have a matrix of drops that is gonna fall down. 
Kind o the simulation of a 3d water courtain.</p>

<p>As in the Shiffman examples, i'm using a OOP approach, where each particle is an object in an arraylist and when they go too fare are deleted to free memory.</p>

<p>The only difference is that the particle system is executed in a parallel thread and the main one just get a copy of the particles to represent them, when is needed.</p>

<p>What i don't understand, is why the sketch slow down so much when the drops approach the distance where they are deleted.
After all, the check happen to every loop anyway. Is there some technique to make this more efficient?</p>

<pre><code>import peasy.*;

PeasyCam cam;

ParticleSystem ps;

void setup() {

  size(600, 600, P3D);

  cam = new PeasyCam(this, 15, 30, 15, 100);
  cam.setMinimumDistance(50);
  cam.setMaximumDistance(500);
  ps = new ParticleSystem();
}

void draw() {

  background(255);
  noFill();
  strokeWeight(1);

  pushMatrix();
  translate(15, -5, 15);
  box(30, 10, 30);
  popMatrix();

  pushMatrix();
  translate(15, 50, 15);
  box(30, 30, 30);
  popMatrix();

  pushMatrix();
  strokeWeight(0.1);

  ArrayList&lt;Particle&gt; particles = ps.particles();
  for (int i = 0; i&lt; particles.size(); i++ ) {

    point(
      particles.get(i).position.x, 
      particles.get(i).position.y, 
      particles.get(i).position.z
      );
  }

  popMatrix();
}

public  class ParticleSystem implements Runnable {

  boolean loop = true;
  ArrayList&lt;Particle&gt; particles;

  long lastUpdate;
  int updateInterval = 10;

  float maxTravelDistance = 35 ;
  float pRF = 0.005;  // particlesRandomFactor


  public ParticleSystem() {


    particles = new ArrayList&lt;Particle&gt;();

    for (int x = 0; x &lt; 15; x++) {
      for (int z = 0; z &lt; 15; z++) {
        for (int i = 0; i &lt; 1000; i++)
        {
          particles.add(new Particle(new PVector(x*2, 0, z*2), new PVector(random(-pRF, pRF), random(-pRF, pRF), random(-pRF, pRF))));
        }
      }
    }
    new Thread(this).start();
    println(particles.size());
  }

  @ Override
  public void run() {

    while (loop) {
      if (millis()-lastUpdate &gt; updateInterval &amp;&amp; millis() &gt; 3000) {
        if (particles.size() &gt;0) {
          for (int i = particles.size()-1; i&gt;0; i--) {
            if (particles.get(i).position.y &gt; maxTravelDistance) particles.remove(i);
            else  particles.get(i).update();
          }
        }
        lastUpdate = millis();
      }
    }
  }


  ///////////particles
  public synchronized ArrayList&lt;Particle&gt; particles() {
    return particles;
  }




  public synchronized PVector[] getPositions() {

    //ArrayList&lt;Particle&gt;particlesToExport = particles().toArray(new Particle[particles.size()]);

    ArrayList&lt;Particle&gt;particlesToExport = particles;
    PVector[] output = new PVector[particlesToExport.size()];

    for (int i = 0; i &lt; output.length; i++)
    {
      output[i] = particlesToExport.get(i).position();
    }

    return output;
  }
}


public  class  Particle {

  float mass;
  boolean isDead = false;
  float airDrag = 0.95;


  PVector position;
  PVector oldPosition;

  PVector speed;
  PVector acceleration;

  public Particle(PVector p, PVector s) {
    mass = random(0.9, 1.1);
    position = p;
    speed = s;
    acceleration = new PVector(0, 0.02*mass, 0);
  }

  void update() {
    //oldPosition = position;
    if (abs(speed.x) &gt;=0.05 || abs(speed.z) &gt;= 0.05) speed.mult(airDrag);
    if (!(speed.y &gt; 10)) speed.add(acceleration);
    position.add(speed);
  }

  ///////////position
  public synchronized void position(PVector input) {
    position = input;
  }
  public synchronized PVector position() {
    return position;
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>how to delete elements from canvas graphics in p5.js</title>
      <link>https://forum.processing.org/two/discussion/22913/how-to-delete-elements-from-canvas-graphics-in-p5-js</link>
      <pubDate>Sun, 04 Jun 2017 07:29:29 +0000</pubDate>
      <dc:creator>Adeeba</dc:creator>
      <guid isPermaLink="false">22913@/two/discussions</guid>
      <description><![CDATA[<p>how to delete elements from canvas graphics in p5.js</p>

<pre><code>function setup(){   
            canvas=createCanvas(1000,1000);
            canvsGraphics = createGraphics(1000,1000);
        }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Problem regarding ArrayList</title>
      <link>https://forum.processing.org/two/discussion/22678/problem-regarding-arraylist</link>
      <pubDate>Sat, 20 May 2017 10:18:34 +0000</pubDate>
      <dc:creator>jcov</dc:creator>
      <guid isPermaLink="false">22678@/two/discussions</guid>
      <description><![CDATA[<p>Hey,</p>

<p>Just wondering if anyone can help me out with this bit of code.</p>

<p>I'm trying to remove an ellipse that's drawn to the screen after I've clicked it. Not sure how to approach the problem?</p>

<pre><code>ArrayList &lt;ball&gt; balls = new ArrayList &lt;ball&gt;();
int numOfBalls = 5;
float dist;

class ball {

  float x, y;

  ball() {

    x = random(20, width-20);
    y = random(20, height-20);
  }

  void draw_ball () {
    ellipse(x, y, 20, 20);
  }

  void remove_ball () {
    for (int i = numOfBalls-1; i &gt;=0; i--) {

      dist = sqrt((x-mouseX) * (x-mouseX) + (y-mouseY) * (y-mouseY));
      if (dist &lt;= 20) {

        balls.remove(i);
      }
    }
  }
}

void setup () {
  size(500, 500);
  for ( int i = 0; i &lt; numOfBalls; i++)
    balls.add(new ball());
}

void draw () {
  for ( int i = 0; i &lt; numOfBalls; i++)
    balls.get(i).draw_ball();
}

void mousePressed() {

  remove_ball();
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Removing an object in an array upon collision</title>
      <link>https://forum.processing.org/two/discussion/21902/removing-an-object-in-an-array-upon-collision</link>
      <pubDate>Sun, 09 Apr 2017 10:45:14 +0000</pubDate>
      <dc:creator>Dreeww</dc:creator>
      <guid isPermaLink="false">21902@/two/discussions</guid>
      <description><![CDATA[<p>Hi, i was wondering if anyone could help in regards to in regards collision detection
    void collisionDetection(){
      for(int i = 0; i &lt; aesteroidBelt.size(); i++){
        Aesteroid current = aesteroidBelt.get(i);</p>

<pre><code>    for(int b = 0; b &lt; bullets.size(); b++)
    {
      Bullet currentBullet = bullets.get(b);
        if(dist()){
        bullets.remove(b);
        aesteroidBelt.remove(i);
</code></pre>

<p>Cant figure out the values to use for keeps telling me that booleans are not accept and only floats are.</p>

<p>These are the variables i have</p>

<pre><code>int n=12;

PVector ship;

//Initilaizes Variables used
float bulletSpeed = 5;
float angle = 0;
float targetAngle = 0;
float rotation = 0.05;
float xSpeed = random(0.6, 2.5);
float ySpeed = random(0.6, 2.5);
float x = random(1, 590);
float y = random(1, 390);
</code></pre>

<p>My Aesteroids are also a random PVector every time you run this code(part which i am stuck on)</p>
]]></description>
   </item>
   <item>
      <title>How to nicely extract data from a .csv table and display it ?</title>
      <link>https://forum.processing.org/two/discussion/21854/how-to-nicely-extract-data-from-a-csv-table-and-display-it</link>
      <pubDate>Thu, 06 Apr 2017 10:04:58 +0000</pubDate>
      <dc:creator>Spiritofthecode</dc:creator>
      <guid isPermaLink="false">21854@/two/discussions</guid>
      <description><![CDATA[<p>Hello there !</p>

<p>I've got 2 csv files on my hand ; the first  listing restaurants, with 3 columns(coordinate x, coordinate y, restaurant name) and another listing deliveries (coordinate x, delivery coordinate y , name of the restaurante the delivery was done by).</p>

<p>I need to :
1) Display the number of deliveries made for each restaurant. 
2) The average distance of the deliveries for each restaurant (distance being calculated by this formula = sqrt(sq(x1-x2)+sq(y1-y2) at least I figured something out :p)</p>

<p>For the first, I made a class which looks like this :</p>

<p>Then I'm trying to go trought the deliveries table and change the arraylist of objects so that when the string happens to be the same in a row and the arraylist object the object counts gets to +1. But it doesn't seem to work. Any tips appreciated for the step 2, also.</p>
]]></description>
   </item>
   <item>
      <title>Bubbles Blinking</title>
      <link>https://forum.processing.org/two/discussion/21785/bubbles-blinking</link>
      <pubDate>Mon, 03 Apr 2017 22:36:48 +0000</pubDate>
      <dc:creator>PRouse</dc:creator>
      <guid isPermaLink="false">21785@/two/discussions</guid>
      <description><![CDATA[<p>I have a pretty straight forward code written that produces bubbles across the bottom of the screen continuously, and once they reach the top they are removed. However, I've noticed random bubbles will blink a few times before they reach the top of the screen. I'm just wondering why that is.</p>

<p>Here's the code:</p>

<p>Main</p>

<pre><code>ArrayList&lt;Bubble&gt; bubbles;
int add = 0;
int initial = 10;

void setup(){
  fullScreen();
  bubbles = new ArrayList&lt;Bubble&gt;();
}

void draw(){
  background(0);
  bubbles.add(new Bubble(random_generator()));

  //If bubble gets to the top it is removed
  for (int i = 0; i &lt; bubbles.size(); i++){
    Bubble b = bubbles.get(i);
    b.ascend();
    b.display();
    if (b.top()){
      bubbles.remove(i);
    }

  }
}

int random_generator(){
  int r = int(random(10, 100));
  return r;
}
</code></pre>

<p>Class</p>

<pre><code>class Bubble{

  float x;
  float y;
  float diameter;
  float yspeed;

  //constructor
  Bubble(float tempD){
    x = random(width);
    y = height;
    diameter = tempD;
    yspeed = random(2.5, 10.5);
  }

  //moves bubble upwards, and randomly from side-to-side
  void ascend(){
    y = y - yspeed;
    x = x + random(-2, 2);
  }

  //displays bubble
  void display(){
    noStroke();
    fill(231, 254, 255, 200);
    ellipse(x, y, diameter, diameter);
  }

  //checks if bubble is at the top of the screen
  boolean top(){
    if (y &lt; 0){
      return true;
    }
    else{
      return false;
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Re-use removed object from ArrayList?</title>
      <link>https://forum.processing.org/two/discussion/21677/re-use-removed-object-from-arraylist</link>
      <pubDate>Wed, 29 Mar 2017 12:03:51 +0000</pubDate>
      <dc:creator>Arya</dc:creator>
      <guid isPermaLink="false">21677@/two/discussions</guid>
      <description><![CDATA[<p>I just got a little familiar with using ArrayLists in my jump n run game, but I am not yet sure about how it all works.
So, I have a collision detection that removes objects after collision with the player.
Now I want to generate levels and I have made some kind of "portal" that the player has to collide with after hitting a certain score. It works fine, the player touches the portal, gets "teleported" to the next level and the game speed increases. The portal is removed based on the same principle, as I did before when the player collects the bonusses, which then disappear.
However, I need to re-use the portal to get into the next level after hitting another score..
I guess the portal is then gone, thats why it doesnt work..</p>

<p>Main Program
    ArrayListteleport=new ArrayList();
    boolean goToNextLevel;
    int level=1;
    int score=0;
    int hits=0;</p>

<pre><code>void setup()
{
  size(600, 300);
  startGame();
}

void draw()
{          
 if (gameStart) {
    getItGoing();
  }
}

void startGame()
{
   gameStart = false;

  //portal
  teleport=new ArrayList&lt;Portal&gt;();
  teleport.add(new Portal(width/2, height/2, 50, 100));
  teleport.add(new Portal(width/2, height/2, 50, 100));

  //player; initial position
  player=new Player(50, height-70, 30, 40, height-70);      
}

void getItGoing() //start game after shift key is pressed
{
  if (millis()&lt;startOfGame+durationOfGame) { 
//if game is still running and a certain Score is hit, boolean goToNextLevel turns true and Portal is displayed
    for (int i=0; i&lt;teleport.size(); i++) {
      if (goToNextLevel==true) {
        Portal portal = (Portal) teleport.get(i);
        portal.displayPortal();
      }
    }
  }
}

boolean beamPlayer(float x, float y, float w, float h)
{  
  for (int i=0; i&lt;teleport.size(); i++)
  {
    if (teleport.get(i).teleportationDone(x, y, w, h)) {
      teleport.remove(i);
      return true;
    }
  }
  return false;
}
</code></pre>

<p>Then the Portal class</p>

<pre><code>    class Portal {

      int portalX = 0;
      int portalY = 0;
      int portalWidth =0;
      int portalHeight= 0;

      Portal (int pX, int pY, int pW, int pH) {

        portalX = pX;
        portalY = pY;
        portalWidth = pW;
        portalHeight = pH;
      }

      void displayPortal() {

        fill(0,0,0,100);
        ellipse(portalX, portalY, portalWidth, portalHeight);
      }


     boolean teleportationDone(float x, float y, float w, float h)
      {
        if ((x+w&gt;=portalX-portalWidth/2) &amp;&amp; (x&lt;(portalWidth/2+portalX)) &amp;&amp;
            ((y+h) &gt;= portalY-portalHeight/2) &amp;&amp; (y &lt; (portalY-portalHeight/2)))
        {
          println("teleported to next level");
          level+=1;
          return true;
        }
        return false;
      }
    }
</code></pre>

<p>and the Player class</p>

<pre><code>class Player {
    boolean teleported = false;
    float playerX, playerY, playerWidth, playerHeight;

 void drawPlayer()
  {
    fill(255);
    rect(playerX, playerY, playerWidth, playerHeight);
  }

  void update()
  {
    teleported = false; //initial state: not collecting carrots
    if (beamPlayer(playerX, playerY, playerWidth, playerHeight))
    {
      //if(!collected) player.score++;
      teleported=true;
      //break not needed here, cause im not using a for loop to break out from like with carrots/platforms
    }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Accessing a class through an arrayList in another class</title>
      <link>https://forum.processing.org/two/discussion/21670/accessing-a-class-through-an-arraylist-in-another-class</link>
      <pubDate>Wed, 29 Mar 2017 08:19:17 +0000</pubDate>
      <dc:creator>Arya</dc:creator>
      <guid isPermaLink="false">21670@/two/discussions</guid>
      <description><![CDATA[<p>I have a class that I want to be accessed by another class and only in there. (in a little game)
So, my structure is that I have the main program that calls the class Tile and then everything runs over Tile.
In Tile, I want to access the class Carrots (that are supposed to be collected by the player). I used normal Arrays so far for the other things that get displayed in Tile, but I want the carrots to be removed after collision and read about ArrayLists for doing so.
However, I cant even get it to show the carrots once I have them in an ArrayList.. could you help me with that? I hope that once I know how to implement them in the first place, Ill figure how to remove objects from the ArrayList.</p>

<pre><code>class Tile
{
  Platform[]platforms = new Platform[3];
  ArrayList&lt;Carrots&gt;karotten;

  float posX=0;
  float posY=0; 
  float Width=0;
  float Height=0;
  float speedX = 1;

  Tile (float x, float y, float w, float h)
  {
    posX = x;
    posY = y;
    Width = w;
    Height = h;

    for (int i=0; i&lt;platforms.length; i++) {
      platforms[i] = new Platform(100+random(100)+i*150, height-70, 30, 40);
    }

    karotten=new ArrayList&lt;Carrots&gt;();
    for (int i=0; i&lt;karotten.size(); i++) {
    karotten.add(new Carrots(random(150), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(150,250), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(250,350), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(350,450), random(height-200, height-150), 10, 20));
    karotten.add(new Carrots(random(450,550), random(height-200, height-150), 10, 20));
    }
  void display()
  {
    for (int i=0; i&lt;platforms.length; i++) {
      platforms[i].drawPlatform(posX);
    }

    for(int i=0; i&lt;karotten.size(); i++) {
      Carrots carrots = (Carrots) karotten.get(i);
      carrots.displayCarrots(posX);
    }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>I'm trying to delete two objects from their respectives arrays when they collide.</title>
      <link>https://forum.processing.org/two/discussion/21542/i-m-trying-to-delete-two-objects-from-their-respectives-arrays-when-they-collide</link>
      <pubDate>Wed, 22 Mar 2017 21:39:29 +0000</pubDate>
      <dc:creator>catatau2001</dc:creator>
      <guid isPermaLink="false">21542@/two/discussions</guid>
      <description><![CDATA[<p>But I'm getting IndexOutOfBonds on the third for inside draw(). I know that the reason is because I'm removing an object from an array while it's on a loop, but I can't figure out a way to do it without this error coming up.</p>

<p>MAIN TAB:</p>

<pre><code>int naveX, naveY;
int movimentoTotal;
int tempoInimigo;

boolean tiroVisivel;
boolean naveDireita, naveEsquerda;
boolean removerTiro, removerInimigo;

ArrayList&lt;Tiro&gt; tiros;
ArrayList&lt;Inimigo&gt; inimigos;

void setup() {
  size (800, 600);

  naveX = 375; 
  naveY = height - 120;

  naveDireita = naveEsquerda = false; 

  tiros = new ArrayList&lt;Tiro&gt;();
  inimigos = new ArrayList&lt;Inimigo&gt;();
}

void draw() {
  translate (0, -(naveY - 480));
  background (0);

  nave();
  movimentoNave();

  naveY = naveY - 1;
  movimentoTotal = movimentoTotal + 1;

  int numTiros =  tiros.size();
  for (int i = numTiros - 1; i &gt;= 0; i = i - 1) {
    tiros.get(i).display();
    tiros.get(i).update();
    if (tiros.get(i).deletarTiro == true || removerTiro == true) {
      tiros.remove(tiros.get(i));
    }
  }
  //println (numTiros);

  if (millis() &gt; tempoInimigo + 1500) {
    tempoInimigo =  millis();
    inimigos.add(new Inimigo());
  }

  int numInimigos = inimigos.size();
  for (int i = numInimigos - 1; i &gt;=0; i = i - 1) {
    inimigos.get(i).display();
    inimigos.get(i).update();
    if (inimigos.get(i).deletarInimigo == true || removerInimigo == true) {
      inimigos.remove(inimigos.get(i));
    }
  }

  //println("Número inimigos é: " + numInimigos);

  for (int i = numTiros - 1; i &gt;= 0; i = i - 1) {
    for (int j = numInimigos - 1; j &gt;= 0; j = j - 1) {
      float distance = dist(tiros.get(i).tiroX, tiros.get(i).tiroY, inimigos.get(j).inimigoX, inimigos.get(j).inimigoY);
      if (distance &lt; 6) {
        removerTiro = true;
        removerInimigo = true;
      }
    }
  }
}

void nave() {
  stroke (255);
  fill (255, 0, 0);
  rect (naveX, naveY, 50, 100);
}

void movimentoNave() {
  if (naveEsquerda == true &amp;&amp; naveX &gt; 0) {
    naveX = naveX - 5;
  }
  if (naveDireita == true &amp;&amp; naveX &lt; width - 50) {
    naveX = naveX + 5;
  }
}



void keyPressed() {
  //create a new shot.
  if (key == ' ') {
    tiros.add(new Tiro(naveX + 20, naveY - 30));
  }

  if (key == 'a' || key == 'A') {
    naveEsquerda = true;
  }
  if (key == 'd' || key == 'D') {
    naveDireita = true;
  }

  if (key == 'r' || key == 'R') {
    setup();
  }
}

void keyReleased() {
  if (key == 'a' || key == 'A') {
    naveEsquerda = false;
  }
  if (key == 'd' || key == 'D') {
    naveDireita = false;
  }
}
</code></pre>

<p>ENEMYS TAB:</p>

<pre><code>public class Inimigo {

  public int inimigoX =  int (random(15, width - 15));
  public int inimigoY =  -100 - movimentoTotal;
  public boolean deletarInimigo;

  public Inimigo() {
    //this.inimigoX = inimigoX;
    //this.inimigoY = inimigoY;
    deletarInimigo = false;
    removerInimigo = false;
  }

  void mostrar() {
    stroke (255);
    fill (0, 100, 255);
    rect (inimigoX, inimigoY, 30, 50);
  }

  void deletar() {
    if (inimigoY &gt; height - movimentoTotal) {
      deletarInimigo = true;
    }
  }
}
</code></pre>

<p>PROJECTILES TAB:</p>

<pre><code>public class Tiro {

  public int tiroX;
  public int tiroY;
  public boolean deletarTiro;

  public Tiro (int tiroX, int tiroY) {
    this.tiroX = tiroX;
    this.tiroY = tiroY;
    deletarTiro = false;
    removerTiro = false;
  }

  void display() {
    stroke (255);
    fill (255, 0, 100);
    rect (tiroX, tiroY, 10, 20);
  }

  void update() {
    if (tiroY &gt; 0 - movimentoTotal) {
      tiroY = tiroY - 10;
    } else {
      deletarTiro = true;
    }
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Help with object collision</title>
      <link>https://forum.processing.org/two/discussion/21154/help-with-object-collision</link>
      <pubDate>Sat, 04 Mar 2017 18:49:39 +0000</pubDate>
      <dc:creator>Kang01</dc:creator>
      <guid isPermaLink="false">21154@/two/discussions</guid>
      <description><![CDATA[<p>I am currently working on a game where you shoot stuff down in space
and I cant figure out how to check if the bullets are hitting the targets
heres the code</p>

<pre><code>ArrayList &lt;Bullet&gt; bullets;
float numOfStars = 500;
PImage spaceShip;


float [] x = new float[int(numOfStars)];
float [] y = new float[int(numOfStars)];
float [] speed = new float[int(numOfStars)];
float [] bullet;
//Bullet = new Bullet();
float bulletSpeed;
boolean Bullet;










void setup() {
   bullets = new ArrayList();
  fullScreen();
  //size(500, 400);
  background(0);
  stroke(255);
  spaceShip = loadImage("Spaceship2.png");

  noCursor();



  int i = 0;
  while (i &lt; numOfStars) {
    x[i]= random(0, width);
    y[i] = random(0, height);
    speed[i] = random(1, 5);
    i = i +1;
  }
}


void draw() {
  background(0);
  removeToLimit(100);
  moveAll();
  displayAll();
  //bulletSpeed = bulletSpeed +5;







  //draw triangle
  //triangle(mouseX,mouseY-6,mouseX +20, mouseY,mouseX, mouseY +6);

  //rotate(radians(180));{
  image(spaceShip, mouseX-10, mouseY);
  //}

  int i = 0;
  while (i &lt; numOfStars) {
    float co = map(speed[i], 1, 5, 100, 255);
    stroke(co);
    strokeWeight(speed[i]);
    point(x[i], y[i]);



    x[i] = x[i] -speed[i]/ 2;

    if (x[i] &lt; 0) {
      x[i] = width;
    }
    i = i+5;
  }






  //if (mousePressed == true) {
  // Bullet = true;
  //}





  //  if (Bullet == true) {
  //    rect(mouseX -10 +bulletSpeed, mouseY, 40,10);
  //    fill(#03FC3E);


  //  }







}



class Bullet//bullet class
{
  float x;
  float y;
  float speed;
  Bullet(float tx, float ty)
  {
    x = tx;
    y = ty;
  }
  void display()
  {
     rect(x,y+20, 40,10);
     rect(x,y+80,40,10);
  fill(#03FC3E);
    //stroke(255);
    //point(x,y);
  }
  void move()
  {
    x+= 20;
  }
}

void removeToLimit(int maxLength)
{
  while(bullets.size() &gt; maxLength)
  {
    bullets.remove(0);
  }
}
void moveAll()
{
  for(Bullet temp : bullets)
  {
    temp.move();
  }
}
void displayAll()
{
  for(Bullet temp : bullets)
  {
    temp.display();
  }
}
void mousePressed()//add a new bullet if mouse is clicked
{
  Bullet temp = new Bullet(mouseX,mouseY);
  bullets.add(temp);
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Remove objects form arraylist and have them added to new arraylist</title>
      <link>https://forum.processing.org/two/discussion/20858/remove-objects-form-arraylist-and-have-them-added-to-new-arraylist</link>
      <pubDate>Fri, 17 Feb 2017 22:28:17 +0000</pubDate>
      <dc:creator>MRoden1993</dc:creator>
      <guid isPermaLink="false">20858@/two/discussions</guid>
      <description><![CDATA[<p>Hi. I have a question about some code. I have some code that other members were kind enough to help me with. Within the code a series of numbers are generated and then used to draw lines across the page. So for example the code might generate the numbers 1, 5, 10, 17 etc... 1 line will then be drawn in the top left corner of the page and then 5 lines drawn at a different point along the y axis etc...</p>

<p>What I would like to add to the code is the ability to remove random objects from the arraylist and then have them added to a new arraylist that would draw lines descending from the top right corner of the page if you press a key or something like that. So if you presses a key it would take a few lines from the left of the page and reposition them on the right.</p>

<p>Any help would be much appreciated. Thanks, Michael</p>

<pre><code>ArrayList&lt;Line&gt; lines;

    int z = 0;
    int a = 0;
    int b = 0;

    int startx = 500;
    int starty = 500;
    int endy = 50;

    int[] numbers = new int[20];

    void setup() {

      size(1000, 1000);
      frameRate(4);
      lines = new ArrayList&lt;Line&gt;();

      int num =0;
      for (int x =0; x&lt; 20; x++) {
        num +=int(random(10, 50));
        print((numbers [x]= (num % 60))  + ", ");
      }
      numbers = sort(numbers);

      println("\nsorted");
      println(numbers);
      fill(0);

    }

    void draw() {

      background(255);

      text("Current "+z,width/2,height*0.80);

      int nn=-1;
      for (int i=0; i&lt;=z; i++)
        nn+=numbers[i] -1;

      generateLines();

      for (int i = 0; i &lt;nn ; i++) {   
        Line myline = lines.get(i);
        myline.draw();

         }

      }


    void generateLines() {

      if (z &lt; numbers.length -1 ) {
      z++; }


      for (int j=0;j&lt;numbers[z] -1;j++){

        lines.add(new Line(startx, starty, random(50, 250), 50*z)); }

      } 

class Line {

  float sx;
  float sy;
  float ex;
  float ey;

  Line(float startX, float startY, float endX, float endY) {

    sx = startX;
    sy = startY;
    ex = endX;
    ey = endY;
  }

  void draw() {

    stroke(0);
    line(ex, ey, sx, sy);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Create 10 instances of an object (Python)</title>
      <link>https://forum.processing.org/two/discussion/19200/create-10-instances-of-an-object-python</link>
      <pubDate>Mon, 21 Nov 2016 20:50:07 +0000</pubDate>
      <dc:creator>juicy</dc:creator>
      <guid isPermaLink="false">19200@/two/discussions</guid>
      <description><![CDATA[<p>Hello Forum,</p>

<p>I got a question:
First off: I'm using Python Mode.
I'm trying to instantiate an object 10 times, but whatever i do ends up in the ellipses getting a tremendous speed boost.
The idea is: Create 10 ellipses all spawning on different locations and with different velocity.
Is this possible using lists?
Here is the code, creating 1 instance of the object:</p>

<pre><code>from BallTab import Ball

def setup():
    global myFirstBall
    size(800, 800)
    myFirstBall = Ball(random(50, 750), random(50, 750), 2, 3, 100)


def draw():
    global myFirstBall
    background(69, 69, 69) 
    myFirstBall.display()
    myFirstBall.move()
    if myFirstBall.y &gt; 750:
        myFirstBall.ys = -2
    if myFirstBall.x &gt; 750:
        myFirstBall.xs = -3
    if myFirstBall.y &lt; 50:
        myFirstBall.ys = 2
    if myFirstBall.x &lt; 50:
        myFirstBall.xs = 3
</code></pre>

<p>BallTab:</p>

<pre><code>class Ball(object):
    def __init__(self, xPos, yPos, xSpeed, ySpeed, radius):
        self.x = xPos
        self.y = yPos
        self.xs = xSpeed
        self.ys = ySpeed
        self.r = radius

    def display(self):
        ellipse(self.x, self.y, self.r, self.r)

    def move(self):
        self.x += self.xs
        self.y += self.ys
</code></pre>
]]></description>
   </item>
   <item>
      <title>collision - how to avoid indexOutOfBoundsException?</title>
      <link>https://forum.processing.org/two/discussion/19284/collision-how-to-avoid-indexoutofboundsexception</link>
      <pubDate>Thu, 24 Nov 2016 23:37:50 +0000</pubDate>
      <dc:creator>Laursen44</dc:creator>
      <guid isPermaLink="false">19284@/two/discussions</guid>
      <description><![CDATA[<p>Hello processing forum!</p>

<p>I have made a game where you fly around with a spaceship, you need to avoid incoming meteors or shoot them. 
But sometimes, when two meteors are on top of eachother, and you shoot them i get an OutOfBounds error, when they are deleted from the ArrayList.</p>

<p><img src="" alt="" /></p>

<p><img src="https://forum.processing.org/two/uploads/imageupload/961/76I87OKX22EG.JPG" alt="error OutOfBounds" title="error OutOfBounds" /></p>

<p>This is the collision detection method:</p>

<pre><code>  void bulletCollideMeteor() {
    for (int i = particles.size()-1; i &gt;= 0; i--) {
      Bullet bullet = particles.get(i);
      for (int j = meteors.size()-1; j &gt;= 0; j--) {
        Meteor meteor = meteors.get(j);

        float d = dist(bullet.x, bullet.y, meteor.x, meteor.y);

        if (d &lt; bulletR + meteorR) {
          bulletHitMeteor = true;
        } else {
          bulletHitMeteor = false;
        }

        if (bulletHitMeteor) {
          particles.remove(i);
          meteors.remove(j);
          score += 10;
          explosion.rewind();
          explosion.play();
        }
      }
    }
  }
</code></pre>

<p>The meteors spawn at random pre-determined locations at y = -200 and then get a random speed.</p>

<pre><code>  void meteor() {
    int rLoc = int(random(0, 6));
    float xdir =int(random(-4, 4));
    float ydir =int(random(8, 16));
    meteors.add(new Meteor(vectors[rLoc].x, vectors[rLoc].y, xdir, ydir));
</code></pre>

<p>can you think of any way to solve this problem?</p>

<p>I have thought of having the meteors x-speed mulitplied by -1 to change their direction. But this fails when i cant acess their x-values separately.</p>

<p>thanks in advance!</p>
]]></description>
   </item>
   </channel>
</rss>