如何访问存储为数组中对象的形状的坐标
How to access the co-ordinates of a shape stored as an object in an array
我已经将几条随机绘制的线的坐标存储在一个对象数组中。
我现在希望能够以编程方式操作数组中所有对象中的例如 x1。我不知道该怎么做,甚至不知道如何查看存储线的坐标。如果我这样做 println()
我只是得到对象的内存引用。
目前的代码如下:
class Line{
public float x1, y1, x2, y2;
public Line(float x1, float y1, float x2, float y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void draw(){
line(x1, y1, x2, y2);
float rot = random(360);
rotate(rot);
}
//public boolean intersects(Line other){
// //left as exercise for reader
//}
}
ArrayList<Line> lines = new ArrayList<Line>();
void setup(){
background(204);
size(600, 600);
for(int i = 0; i < 20; i++){
float r = random(500);
float s = random(500);
lines.add(new Line(r,s,r+10,s+10));
printArray(lines);
for(Line line : lines){
line.draw();
}
}
}
简单地使用点符号。使用您的 Line class,您可以使用 new
关键字和构造函数(与 class 同名的特殊函数)创建一个 Line 对象(或实例):
Line aLine = new Lines(0,100,200,300);
获得实例后,您可以使用实例名称访问它的变量(称为属性),然后是 .
符号,然后是变量名称:
println("aLine's x1 is " + aLine.x1);
在您的示例代码中,在 draw()
函数中,您访问每个 Line 实例的 .draw() 函数(称为方法):
for(Line line : lines){
line.draw();
}
}
只需使用相同的概念访问 Line 的其他成员即可:
for(Line line : lines){
//wiggle first point's x coordinate a little (read/write x1 property)
line.x1 = random(line.x1 - 3,line.x1 + 3);
line.draw();
}
}
请务必阅读 Daniel Shiffman's Objects tutorial 了解更多详情。
我已经将几条随机绘制的线的坐标存储在一个对象数组中。
我现在希望能够以编程方式操作数组中所有对象中的例如 x1。我不知道该怎么做,甚至不知道如何查看存储线的坐标。如果我这样做 println()
我只是得到对象的内存引用。
目前的代码如下:
class Line{
public float x1, y1, x2, y2;
public Line(float x1, float y1, float x2, float y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public void draw(){
line(x1, y1, x2, y2);
float rot = random(360);
rotate(rot);
}
//public boolean intersects(Line other){
// //left as exercise for reader
//}
}
ArrayList<Line> lines = new ArrayList<Line>();
void setup(){
background(204);
size(600, 600);
for(int i = 0; i < 20; i++){
float r = random(500);
float s = random(500);
lines.add(new Line(r,s,r+10,s+10));
printArray(lines);
for(Line line : lines){
line.draw();
}
}
}
简单地使用点符号。使用您的 Line class,您可以使用 new
关键字和构造函数(与 class 同名的特殊函数)创建一个 Line 对象(或实例):
Line aLine = new Lines(0,100,200,300);
获得实例后,您可以使用实例名称访问它的变量(称为属性),然后是 .
符号,然后是变量名称:
println("aLine's x1 is " + aLine.x1);
在您的示例代码中,在 draw()
函数中,您访问每个 Line 实例的 .draw() 函数(称为方法):
for(Line line : lines){
line.draw();
}
}
只需使用相同的概念访问 Line 的其他成员即可:
for(Line line : lines){
//wiggle first point's x coordinate a little (read/write x1 property)
line.x1 = random(line.x1 - 3,line.x1 + 3);
line.draw();
}
}
请务必阅读 Daniel Shiffman's Objects tutorial 了解更多详情。