2016-11-24 59 views
-1

開始我做了一個簡單的代碼,檢查2條線是否基於由它們的x和y座標給出的4個點相互碰撞。它檢查兩條線的角度(我的代碼中的變量k)是否相同,在這種情況下它們是平行的,否則它們會發生碰撞。角度(k)基於數學等式Click here [k =(y2-y1)/(x2-x1)]計算。現在我不知道如何得到他們碰撞的點。如果你能幫助我,我將非常感激。先謝謝你。查找C#中線條交點的座標

我的代碼:(方法I調用來計算角度)類Duzina

static void MetodaTrazenjaPresjeka(Duzina d1, Duzina d2) 
    { 

     int k11 = d1.Krajy - d1.Pocy; //y2-y1 - first line 
     int k12 = d1.Krajx - d1.Pocx; //x2-x1 - first line 
     double k1 = (double)k11/k12; //angle of the first line 
     int k21 = d2.Krajy - d2.Pocy; //y2-y1 - second line 
     int k22 = d2.Krajx - d2.Pocx; //x2-x1 - second line 
     double k2 = (double)k21/k22; //angle of the second line 
     if (k1 == k2) 
     { 
      //they are parallel 
      Console.WriteLine("MOJA METODA:"); 
      Console.WriteLine("-----------------------------------"); 
      Console.Write("Pravci zadani tockama su paralelni!"); 
     } 
     else 
     { 
      //lines are colliding 
      Console.WriteLine("MOJA METODA:"); 
      Console.WriteLine("-----------------------------------"); 
      Console.Write("Pravci zadani tockama se sijeku!"); 
     } 
    } 

代碼:

class Duzina 
{ 
    private int pocx, pocy, krajx, krajy; 
    //read/write attribute for the x coordinate of the first point 
    public int Pocx 
    { 
     get { return pocx; } 
     set { pocx = value; } 
    } 
    //read/write attribute for the y coordinate of the first point 
    public int Pocy 
    { 
     get { return pocy; } 
     set { pocy = value; } 
    } 
    //read/write attribute for the x coordinate of the second point 
    public int Krajx 
    { 
     get { return krajx; } 
     set { krajx = value; } 
    } 
    //read/write attribute for the y coordinate of the second point 
    public int Krajy 
    { 
     get { return krajy; } 
     set { krajy = value; } 
    } 
    //method that will print out coordinates of the given points 
    public void Ispis() 
    { 
     Console.Write("Pocetna tocka: ({0},{1})",Pocx,Pocy); 
     Console.Write("Krajnja tocka: ({0},{1})", Krajx, Krajy); 
    } 
} 
+0

可能重複[你怎麼檢測兩條線段相交?](http://stackoverflow.com/questions/563198/how-do-you-detect -where-two-line-segments-intersect) – KISKE

+0

難道你不想使用自動屬性來縮短代碼嗎? –

+0

我在高中,這是一種方法,以確保我不會忘記我們正在學習的課堂@ThomasWeller –

回答

0

線方程:y = m * x + b

1) m_d1 = (d1.y2 - d1.y1)/(d1.x2 - d1.x1) 
    b_d1 = d1.y1 - m_d1 * d1.x1 
    (same for m_d2 and b_d2) 

2) intersect.y = m_d1 * intersect.x + b_d1 
    intersect.y = m_d2 * intersect.x + b_d2 

3) m_d1 * intersect.x + b_d1 = m_d2 * intersect.x + b_d2 

4) intersect.x = (b_d2 - b_d1)/(m_d1 - m_d2) 

現在塞相交。從4)獲得的x回到e ither方程在2)得到intersection.y

+0

這不是一個編碼問題,而是一個數學問題,所以我提供了數學,你可以編寫代碼(這是微不足道的)。 – Danny