2012-12-05 31 views
1

我正試圖在C#中實現牆跟隨轉向行爲。爲此,我有一個點和一個線段。我需要的是perpendicular point C,因此線段CD垂直於ABhttp://puu.sh/1xrxQ這是場景。重點在移動,所以我需要每次計算它。我是c#的新手,所以我不知道它是如何工作的。在線段AB上找到一個點C,使線段DC垂直於AB。 D是C#中線外的一個點#

這是我嘗試到現在爲止得到它的工作。

private double DotProduct(Point pointA, Point pointB, Point pointC) 
{ 
    Point AB = new Point(); 
    Point BC = new Point(); 
    AB.X = pointB.X - pointA.X; 
    AB.Y = pointB.Y - pointA.Y; 
    BC.X = pointC.X - pointB.X; 
    BC.Y = pointC.Y - pointB.Y; 
    double dot = AB.X * BC.X + AB.Y * BC.Y; 

    return dot; 
} 

//Compute the cross product AB x AC 
private double CrossProduct(Point pointA, Point pointB, Point pointC) 
{ 
    Point AB = new Point(); 
    Point AC = new Point(); 
    AB.X = pointB.X - pointA.X; 
    AB.Y = pointB.Y - pointA.Y; 
    AC.X = pointC.X - pointA.X; 
    AC.Y = pointC.Y - pointA.Y; 
    double cross = AB.X * AC.Y - AB.Y * AC.X; 
    return cross; 
} 

//Compute the distance from A to B 
double Distance(Point pointA, Point pointB) 
{ 
    double d1 = pointA.X - pointB.X; 
    double d2 = pointA.Y - pointB.Y; 

    return Math.Sqrt(d1 * d1 + d2 * d2); 
} 

//Compute the distance from AB to C 
//if isSegment is true, AB is a segment, not a line. 
double LineToPointDistance2D(Point pointA, Point pointB, Point pointC, bool isSegment) 
{ 
    double dist = CrossProduct(pointA, pointB, pointC)/Distance(pointA, pointB); 
    if (isSegment) 
    { 
     double dot1 = DotProduct(pointA, pointB, pointC); 
     if (dot1 > 0) 
      return Distance(pointB, pointC); 

     double dot2 = DotProduct(pointB, pointA, pointC); 
     if (dot2 > 0) 
      return Distance(pointA, pointC); 

    } 
    return Math.Abs(dist); 
} 
+4

如果你需要你學會基本的數學和基本操作之前在C#中,請僱人爲你做的回答。否則,請編輯您的問題,提供您不明白的信息並刪除「儘快幫助我/謝謝您」。 –

+0

你需要任何幫助或只是代碼? – Gille

+0

@AlexeiLevenkov我知道基本的數學。我不明白的是我如何實現它。我很抱歉,我是堆棧溢出的新手,所以我不知道這是如何工作的。 – justinpakulo

回答

1

沒有測試,但是數學這應該工作

Point intersectionPoint(Point A, Point B, Point C) { 
    //check for slope of 0 or undefined 
    if (A.Y == B.Y) return new Point (C.X, A.Y); 
    if (A.X == B.X) return new Point (A.X, C.Y); 
    //slope = (y1 - y2)/(x1 - x2) 
    double slopeAB = (A.Y - B.Y)/(A.X - B.X); 
    //perpendicular slope is the negative reciprocal 
    double slopeCD = -1/slopeAB; 
    //solve for b in y = mx + b of each line 
    // b = y - mx 
    double bAB = A.Y - slopeAB * A.X; 
    double bCD = C.Y - slopeCD * C.X; 
    double dX, dY; 
    //intersection of two lines is m1x + b1 = m2x + b2 
    //solve for x: x = (b2 - b1)/(m1 - m2) 
    //find y by plugging x into one of the equations 
    dX = (bCD - bAB)/(slopeAB - slopeCD); 
    dY = slopeAB * dX + bAB; 
    return new Point(dX, dY); 
} 
相關問題