我有兩個點A和B,它們定義了設備屏幕上的線段加上另一個點C.使用易於編碼的高效和簡短算法(最好使用標準數學庫),我該如何檢查線段AB是否在距離C的距離R內?檢查線段距點
我知道有一種簡單的方法可以找到從一個點到一條線的最短距離,但它假設這條線是無限長的。我擁有的是具有兩個端點的線段。
我認爲這是在數學SE發佈,但決定不是因爲我不想得到所有這些長數學公式作爲答案在https://math.stackexchange.com/questions/2837/how-to-tell-if-a-line-segment-intersects-with-a-circle。我需要的是一個高效可讀的計算機算法,而不是一個正式的數學定理。
P/S:我有需要實現以下目的-C方法骨架:
由於從veredesmarald回答(我已經接受:
typedef struct {
CGPoint a;
CGPoint b;
} CGLineSegment;
+ (BOOL)isLineSegment:(CGLineSegment)line withinRadius:(CGFloat)radius fromPoint:(CGPoint)point {
}
隨溶液EDIT )我已經實現了這個方法,把它作爲其他人的參考:
+ (BOOL)isLineSegment:(CGLineSegment)line withinRadius:(CGFloat)radius fromPoint:(CGPoint)point {
CGPoint v = CGPointMake(line.b.x - line.a.x, line.b.y - line.a.y);
CGPoint w = CGPointMake(point.x - line.a.x, point.y - line.a.y);
CGFloat c1 = dotProduct(w, v);
CGFloat c2 = dotProduct(v, v);
CGFloat d;
if (c1 <= 0) {
d = distance(point, line.a);
}
else if (c2 <= c1) {
d = distance(point, line.b);
}
else {
CGFloat b = c1/c2;
CGPoint Pb = CGPointMake(line.a.x + b * v.x, line.a.y + b * v.y);
d = distance(point, Pb);
}
return d <= radius;
}
CGFloat distance(const CGPoint p1, const CGPoint p2) {
return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
}
CGFloat dotProduct(const CGPoint p1, const CGPoint p2) {
return p1.x * p2.x + p1.y * p2.y;
}
在能夠將其翻譯爲代碼之前,您必須具備(並且最好理解!)涉及的數學。 – 2011-05-20 07:17:23
@巴特基爾斯這是真的,但我正在尋找數學,而不是公式,正如我在我的問題中強調的那樣。我對簡單到中等幾何數學沒有問題。 – Lukman 2011-05-20 07:20:56