開始我做了一個簡單的代碼,檢查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);
}
}
可能重複[你怎麼檢測兩條線段相交?](http://stackoverflow.com/questions/563198/how-do-you-detect -where-two-line-segments-intersect) – KISKE
難道你不想使用自動屬性來縮短代碼嗎? –
我在高中,這是一種方法,以確保我不會忘記我們正在學習的課堂@ThomasWeller –