我正在尝试在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);
}