我在raywenderlich.com上發現了這段代碼片段,但是解釋的鏈接無效。我把答案翻譯成Swift,希望你能理解,即使不知道語言,它實際上也很容易。任何人都可以解釋這裏究竟發生了什麼?謝謝你的幫助。線段交點
class func linesCross(#line1: Line, line2: Line) -> Bool {
let denominator = (line1.end.y - line1.start.y) * (line2.end.x - line2.start.x) -
(line1.end.x - line1.start.x) * (line2.end.y - line2.start.y)
if denominator == 0 { return false } //lines are parallel
let ua = ((line1.end.x - line1.start.x) * (line2.start.y - line1.start.y) -
(line1.end.y - line1.start.y) * (line2.start.x - line1.start.x))/denominator
let ub = ((line2.end.x - line2.start.x) * (line2.start.y - line1.start.y) -
(line2.end.y - line2.start.y) * (line2.start.x - line1.start.x))/denominator
//lines may touch each other - no test for equality here
return ua > 0 && ua < 1 && ub > 0 && ub < 1
}
感謝分母的解釋,但是我已經看到了關於維基百科的文章,但我並沒有真正理解它,因爲我實際上沒有基本的數學知識 - 我只在學校的十年級... – borchero