2016-02-19 91 views
0

我从一个名为Line的类中有一系列随机绘制的线。 我已将所有对象放入数组中。我想用虚线连接彼此靠近的任何线。我能想到的最简单的方法就是说,如果x1坐标是距另一条线的x1 5个像素,然后绘制连接两个x1坐标的虚线。 我遇到的问题是如何比较所有x1坐标和所有其他x1坐标。我认为这应该涉及1.排序数组,然后2.比较连续的数组元素。不过,我只想对x1进行排序,但我不知道如何执行此操作。仅在处理中基于一个属性对对象数组进行排序

这是到目前为止我的代码:

class Line{ 
    public float x1; 
    public float y1; 
    public float x2; 
    public float y2; 
    public color cB; 
    public float rot; 
    public float fat; 

    public Line(float x1, float y1, float x2, float y2, color tempcB, float rot, float fat){ 
     this.x1 = x1; 
     this.y1 = y1; 
     this.x2 = x2; 
     this.y2 = y2; 
     this.cB = tempcB; 
     this.rot = rot; 
     this.fat = fat; 
    };void draw(){ 
     line(x1, y1, x2, y2); 
     //float rot = random(360); 
     float fat = random(5); 
     strokeWeight(fat); 
     ////stroke (red,green,blue,opacity) 
     stroke(fat*100, 0, 0); 
     rotate(rot); 
    } 

} 


//Create array of objects 
ArrayList<Line> lines = new ArrayList<Line>(); 

void setup(){ 
    background(204); 
    size(600, 600); 

    for(int i = 0; i < 200; i++){ 
     float r = random(500); 
     float s = random(500); 
     lines.add(new Line(r,s,r+10,s+10,color(255,255,255),random(360),random(5))); 

    } 

    //Draw out all the lines from the array 

    for(Line line : lines){ 
     line.draw(); 

    //Print them all out 
     println(line.x1,line.y1,line.x2,line.y2,line.cB,line.rot,line.fat); 
} 
} 

//Now create connections between the elements 

//If the x1 of the line is <5 pixels from another line then create a dotted line between the x1 points. 

回答

1

就像其他答案说的那样,你需要比较两个端点,才能做出任何意义。你也不必排序任何东西。

您应该使用dist()函数,而不是只比较x坐标。 dist()函数需要2点,并给你他们的距离。您可以使用此功能来检查两个点是否接近对方与否:

float x1 = 75; 
float y1 = 100; 
float x2 = 25; 
float y2 = 125; 

float distance = dist(x1, y1, x2, y2); 
if(distance < 100){ 
    println("close"); 
} 

您可以通过其他线路使用此功能在您的Line类环和检查近点,或找到最接近点,无论你想要什么。

与往常一样,如果您遇到困难,我建议您尝试一下并提出另一个问题。

0

问题在于一条线是由两个点的事实,尽管被捆绑在一起的(双关语意),你需要检查各点独立的点数。唯一不需要检查的点是同一个Line实例中的其他点。

在这种情况下,您可能最有兴趣拥有一个Point类。然后Line将使用Point实例来定义两端,而不是原始的浮点坐标。通过这种方式,您可以同时拥有一个行列表以及一个Points列表。

通过这种方式,您可以通过x坐标或y坐标对点进行排序,并抓取点的5个像素内的所有点(并且当然不是线实例中的同一个实例或其他点)。

能够将处理拆分为点和线很重要,因为您使用多个视图来处理相同的数据。作为一般规则,只要以当前形式处理麻烦,就应该重新排列所述数据。但是,如果我可以提出建议,那么排序并不是绝对必要的。如果您使用其他所有点检查单个点,则必须根据当前点进行重复排序,而不仅仅是在列表中进行传递以处理足够接近的所有其他点。

+0

嗯。想想看,我可以把线条做成矩形。我想我可以检查中心点的距离。你会介意这个问题吗? –

+0

@SebastianZeki这会简化问题,但我认为这不会完全准确。 – Neil

相关问题