1

我正在尝试在C#. 为此,我有一个点和一个线段。我只需要一个perpendicular point C使线段CD垂直于AB. http://puu.sh/1xrxQ这是场景。点在移动,所以我每次都需要计算它。我是 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

1 回答 1

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);
}
于 2012-12-05T18:57:51.290 回答