我查找了一些与找到点和线的距离有关的公式。在这个页面上,我使用了例14
http://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
我有一个方法变成了这个:
+(bool) checkPointNearBetweenPointsWithPointA:(CGPoint)pointA withPointB:(CGPoint)pointB withPointC:(CGPoint)pointC withLimit:(float)limit {
float A = pointB.x - pointA.x;
float B = pointA.y - pointC.y;
float C = pointA.x - pointC.x;
float D = pointB.y - pointA.y;
float dividend = fabs( A * B ) - ( C * D );
float divisor = sqrt(pow(A,2) + pow(D,2));
float distanceBetweenPointAndLine = dividend / divisor;
if(distanceBetweenPointAndLine < limit){
NSLog(@"distanceBetweenPointAndLine = %f",distanceBetweenPointAndLine);
return YES;
}
return NO;
}
问题是,如果我通过了B点,如果线段被画成B-A,它仍然会返回YES。其他搞砸的事情发生在线的绘制角度。只是想知道我是否需要考虑其他任何事情,如果测试一个点是否接近有限线。我在网上看到的大多数例子都涉及无限长的行。
答案 0 :(得分:0)
尝试下面的代码。线被认为存在于点A和A之间。 B(无论您如何绘制B-> A或A-> B)和C点是考虑距离的考虑点。
+ (bool) checkPointNearBetweenPointsWithPointA:(CGPoint)pointA
withPointB:(CGPoint)pointB
withPointC:(CGPoint)pointC
withLimit:(float)limit
{
CGFloat slopeLine = atan((pointB.y-pointA.y)/(pointB.x-pointA.x) );
CGFloat slopePointToPointA = -1 *atan((pointC.y-pointA.y)/(pointC.x-pointA.x));
CGFloat innerAngle = slopeLine + slopePointToPointA;
CGFloat distanceAC = sqrtf(pow(pointC.y-pointA.y,2) + pow(pointC.x-pointA.x,2));
CGFloat distanceBetweenPointAndLine = fabs(distanceAC * sin(innerAngle));
NSLog(@"distanceBetweenPointAndLine = %f",distanceBetweenPointAndLine);
NSLog(@"is exceeding limit ? %@",distanceBetweenPointAndLine > limit ? @"YES":@"NO");
if(distanceBetweenPointAndLine < limit)
{
return YES;
}
return NO;
}