Skip to content

Commit 66e26c9

Browse files
committed
Fix implementation
1 parent a250341 commit 66e26c9

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

Sources/GameMath/2D Types/2D Physics/Line2D.swift

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,14 @@ public struct Line2D: Sendable {
1717

1818
public extension Line2D {
1919
func pointNear(_ p: Position2) -> Position2 {
20-
// get dot product of e1, e2
21-
let e1 = Position2(p2.x - p1.x, p2.y - p1.y)
22-
let e2 = Position2(p.x - p1.x, p.y - p1.y)
23-
let valDp = e1.dot(e2)
24-
// get squared length of e1
25-
let len2 = e1.squaredLength
26-
return Position2((p1.x + (valDp * e1.x) / len2),
27-
(p1.y + (valDp * e1.y) / len2))
20+
let ab = p2 - p1
21+
let ap = p - p1
22+
23+
var t = ap.dot(ab) / ab.squaredLength
24+
if t < 0 {t = 0}
25+
if t > 1 {t = 1}
26+
27+
return p1 + (ab * t)
2828
}
2929

3030
// TODO: This needs testing

0 commit comments

Comments
 (0)