为什么当我从 class 创建新对象时我的 class 变量似乎被覆盖了?
Why does it seem like my class variable gets overwritten when i make a new object from that class?
当我 运行 代码时,我的第一个实例 Me,似乎正在获取秒实例直接变量,这不是重点。有人能告诉我为什么会这样吗?
该程序现在在屏幕中间生成 3 个圆圈,据推测向 3 个不同的方向移动。但是来自 class 的两个圆圈重叠并朝同一方向移动。尽管对象最初接收不同的向量坐标。
非常感谢 :)
代码:
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);
}
}
两个 Me
对象具有 PVector
的相同 实例 。
这段代码演示了问题:
PVector a = new PVector(1, 1);
PVector b = a;
a.rotate(3.14);
println(b);
要解决此问题,您应该改为传递向量的 copy
:
PVector a = new PVector(1, 1);
PVector b = a.copy();
a.rotate(3.14);
println(b);
当我 运行 代码时,我的第一个实例 Me,似乎正在获取秒实例直接变量,这不是重点。有人能告诉我为什么会这样吗? 该程序现在在屏幕中间生成 3 个圆圈,据推测向 3 个不同的方向移动。但是来自 class 的两个圆圈重叠并朝同一方向移动。尽管对象最初接收不同的向量坐标。 非常感谢 :) 代码:
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);
}
}
两个 Me
对象具有 PVector
的相同 实例 。
这段代码演示了问题:
PVector a = new PVector(1, 1);
PVector b = a;
a.rotate(3.14);
println(b);
要解决此问题,您应该改为传递向量的 copy
:
PVector a = new PVector(1, 1);
PVector b = a.copy();
a.rotate(3.14);
println(b);