Two PVector variables update but only one is changed


#1
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

#2

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
https://processing.org/reference/PVector_copy_.html

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


#3

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


#4

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


#5

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.


#6

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: