Two PVector variables update but only one is changed

PVector p;
PVector newP;

void setup() {
  p = new PVector(500, 300);
  newP = new PVector(500, 300);
}

void draw() {
  newP = p;
  println(newP + " < newP before");

  // Adds to p
  p.add(50, 100);

  println(newP + " < newP after");
  println(p + " < p");
  println();
  delay(5000);
}

When I .add to p, the variable newP changes aswell. Am I missing something here? Does the .add() method do something else than I thought it would? Can someone explain this behavior?

Result:

[ 500.0, 300.0, 0.0 ] < newP before
[ 550.0, 400.0, 0.0 ] < newP after
[ 550.0, 400.0, 0.0 ] < p

the problem is not the ADD,

//p2 = p1;
[ 500.0, 300.0, 0.0 ] < p1 before
[ 500.0, 300.0, 0.0 ] < p2 before
[ 550.0, 400.0, 0.0 ] < p1 after add
[ 500.0, 300.0, 0.0 ] < p2 after add
// but if use
p2 = p1;
[ 500.0, 300.0, 0.0 ] < p1 before
[ 500.0, 300.0, 0.0 ] < p2 before
[ 550.0, 400.0, 0.0 ] < p1 after add
[ 550.0, 400.0, 0.0 ] < p2 after add

but if you use

p2 = p1.copy();
[ 500.0, 300.0, 0.0 ] < p1 before
[ 500.0, 300.0, 0.0 ] < p2 before
[ 550.0, 400.0, 0.0 ] < p1 after add
[ 500.0, 300.0, 0.0 ] < p2 after add

1 Like

Oh. So its an attribute of pvectors to do that. I still dont think its logical but that does the trick. Thanks.

actually it is the way “=” works on objects ( it is referenced not set to equal values )

1 Like

Youre right. I should have known that. Ive been programming for quite some time now, strange that this has never caused me problems like that.

Yeah, these are objects. p and newP are only pointers to these objects. So, if you do newP = p;, it’s setting both of these pointers to the same object, and, as a result,since any manipulations directed at the pointer happen on the object that it’s pointing at, it’s getting reflected in any pointers of that object.

Object oriented programming! :smiley: