Why does it seem like my class variable gets overwritten when i make a new object from that class?

Frederik Roland :

When i run the code, my first instance of Me, seems to be getting the seconds instances direct variable, that's not the point. Can someone tell me why it happens? The program right now spawns 3 circles in the middle of the screen, supposedly moving in 3 different directions. But the two circles from the class overlaps and move in the same direction. Despite the objects originally receiving different Vectorcoordinates. Thanks a lot in advance :) Code:

PVector direct1 = new PVector(1,1);
PVector pos1;
ArrayList<Me> m; 
PVector di1 = new PVector(random(-1,1),random(-1,1));

void setup(){
 size(800,800);
 pos1 = new PVector(width/2,height/2);
 m = new ArrayList<Me>(0);
 for(int i =0; i< 2; i++){
   int a = int(random(-90,90));
  m.add(new Me(di1.rotate(radians(a)))); 
 }
}
void draw(){
 background(0); 
 fill(255);
 circle(pos1.x,pos1.y,50);
 pos1.add(direct1);
 for(int i =0; i< m.size(); i++){
  m.get(i).drawMe(); 
  m.get(i).move();
  //println(m.get(i).direct);
 }
}
class Me{
  PVector pos;
  PVector direct;
 Me(PVector oldDir){
  pos = new PVector(width/2,height/2);
  this.direct = oldDir;
  //this.direct.rotate(radians(random(-90-90)));
  println(direct);

 }
 void drawMe(){
   fill(60);
   circle(pos.x,pos.y,50);
 }
 void move(){
   //println(this.direct);
   pos.add(this.direct);
   println(direct);
 }
}
DutChen18 :

Both Me objects have the same instance of PVector.

This code demonstrates the problem:

PVector a = new PVector(1, 1);
PVector b = a;
a.rotate(3.14);
println(b);

To resolve this you should instead pass a copy of the vector:

PVector a = new PVector(1, 1);
PVector b = a.copy();
a.rotate(3.14);
println(b);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=22924&siteId=1