Using append() to add elements to an array of PVectors

edited October 2013 in Questions about Code

CODE:

PVector current;
PVector[] elements = {};

void setup() {
 size(500,500);
 background(255);
 noStroke();

 current = new PVector(0,0);
}

void draw() {

  for (int i=0; i<elements.length; i++)
  {
   print("(" + elements[i].x + ", " + elements[i].y + ")");
  }
  println("");
}

void mousePressed(){
 println(mouseX + " " +mouseY);
 current.x = mouseX;
 current.y = mouseY;
 elements = (PVector[])append(elements, current);
}

ISSUES: Append seems to add additional elements to the end of the pvector[] elements, however, all elements take the value of the last element. wtF?

Answers

  • edited October 2013
    PVector[] elements = {};
    
    void setup() {
      size(500, 500);
      noLoop();
      background(-1);
      noStroke();
    }
    
    void draw() {
      for (PVector p: elements)
        print("(" + (int) p.x + ", " + (int) p.y + ")" + "\t");
    
      println("\n");
    }
    
    void mousePressed() {
      elements = (PVector[]) append(elements, new PVector(mouseX, mouseY));
      redraw();
    }
    
  • edited October 2013

    You're appending the very same PVector instance into the Array! >:)
    It means when you change any of its fields (x, y, z), that modification reflects across the whole Array!!! @-)
    Take notice that an ArrayList structure is far more appropriate for unknown-sized lists though! :-\"

Sign In or Register to comment.