Skip to content

Commit 66df055

Browse files
authored
Merge pull request #47 from BeyondBelief96/main
Implementing contains(ray, point) function
2 parents c52c1b0 + 3509478 commit 66df055

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

olcUTIL_Geometry2D.h

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@
172172
| intersects | intersects | intersects | intersects | intersects | |
173173
| | | | | | |
174174
---------+--------------+--------------+--------------+--------------+--------------+--------------+
175-
RAY | | | | | | |
175+
RAY | contains | | | | | |
176176
| | | | | | |
177177
| | collision | collision | collision | collision | collision* |
178178
| | intersects | intersects | intersects | intersects | intersects |
@@ -1065,10 +1065,35 @@ namespace olc::utils::geom2d
10651065
return s >= T2(0) && v >= T2(0) && (s + v) <= T2(2) * A * sign;
10661066
}
10671067

1068+
template<typename T1, typename T2>
1069+
inline constexpr bool contains(const ray<T1>& r, const olc::v_2d<T2>& p)
1070+
{
1071+
// Calculate the vector from the ray's origin to point p
1072+
olc::v_2d<T2> op = p - r.origin;
1073+
1074+
// Calculate the dot product between op and the ray's direction
1075+
// This checks if p is in the direction of the ray and not behind the origin
1076+
T2 dotProduct = op.dot(r.direction);
1077+
1078+
if (dotProduct < 0) {
1079+
// p is behind the ray's origin
1080+
return false;
1081+
}
10681082

1083+
// Project op onto the ray's direction (which is already normalized)
1084+
olc::v_2d<T2> projection = { r.direction.x * dotProduct, r.direction.y * dotProduct };
1085+
1086+
// Check if the projection of op onto the ray's direction is equivalent to op
1087+
// This is true if p lies on the ray
1088+
1089+
T2 distance = std::sqrt((projection.x - op.x) * (projection.x - op.x) + (projection.y - op.y) * (projection.y - op.y));
1090+
1091+
// Assuming a small threshold for floating point arithmetic issues
1092+
return distance < epsilon;
1093+
}
10691094

10701095
// overlaps(p,p)
1071-
// Check if point overlaps with point (analagous to contains())
1096+
// Check if point overlaps with point (analogous to contains())
10721097
template<typename T1, typename T2>
10731098
inline constexpr bool overlaps(const olc::v_2d<T1>& p1, const olc::v_2d<T2>& p2)
10741099
{

0 commit comments

Comments
 (0)