Delta operators, and magicaly changing PVectors

Solution at the bottom of post, but I can’t offer an explanation!

I’m trying to make a delta operator to keep track of change in velocity, and I encountered something I have never seen in any language before. I store one pvector into another, manipulate the original, and BOTH experience the same manipulation? What is going on?

class Star {
  PVector pos = new PVector(width/2, height/2); //position
  PVector clk = new PVector(0, 0); //click
  PVector Vel = new PVector(0, 0); //velocity
  PVector oVel = new PVector(0, 0); //old velocity
  PVector dVel = new PVector(0, 0); //delta velocity
  PVector acc = new PVector(0, 0); //acceleration
  int size;
  
  Star (int s){
    size = s;
  }
  void click(float x, float y){
    clk.x = x;
    clk.y = y;
  }
  void update( ){
   
    acc.limit(2);
    acc.x = clk.x - pos.x;
    acc.y = clk.y - pos.y;
    acc.normalize();

   // Start of question area

    oVel = Vel;   //Variable copied
    Vel.add(acc);  //orignal changed
    Vel.mult(0.97);  //and changed again
    println(oVel, Vel);   //oVel, and Vel are always equal, oVel is magically changed

    dVel.sub(Vel, oVel); 
    
    pos.add(Vel);
    
    pushMatrix();
     //ill spare you this long atrocity.
    popMatrix();
    
  }
}

Well I was able to make this work by using the PVector.copy() method.

oVel = Vel.Copy();

//instead of :
oVel = Vel;
1 Like

Hi BodaciousBrian,

When you copy an object like this, you are not making a deep copy. In other words, you are not creating a new object with the same properties.

What you have is another variable that points toward the same object. So if you modify the object through one of those variable, then you modify it for both variable.

The Copy() method actually returns a new PVector with the same properties. That’s why in this case, you can modify one without modifying the other: they are 2 different objects.

2 Likes
1 Like

I thank you both. I had never encountered any thing like that before.