We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a250341 commit 66e26c9Copy full SHA for 66e26c9
Sources/GameMath/2D Types/2D Physics/Line2D.swift
@@ -17,14 +17,14 @@ public struct Line2D: Sendable {
17
18
public extension Line2D {
19
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))
+ let ab = p2 - p1
+ let ap = p - p1
+
+ var t = ap.dot(ab) / ab.squaredLength
+ if t < 0 {t = 0}
+ if t > 1 {t = 1}
+ return p1 + (ab * t)
28
}
29
30
// TODO: This needs testing
0 commit comments