2016-02-19 89 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

相關問題