diff --git a/Source/Shaders/Collisions.hlsl b/Source/Shaders/Collisions.hlsl index e68871e27..4ac81b4aa 100644 --- a/Source/Shaders/Collisions.hlsl +++ b/Source/Shaders/Collisions.hlsl @@ -18,4 +18,21 @@ bool RayHitRect(float3 r, float3 rectCenter, float3 rectX, float3 rectY, float3 return inExtentX && inExtentY; } +// Hits axis-aligned box (boxMin, boxMax) with a line (lineStart, lineEnd). +// Returns the intersections on the line (x - closest, y - furthest). +// Line hits the box if: intersections.x < intersections.y. +// Hit point is: hitPoint = lineStart + (lineEnd - lineStart) * intersections.x/y. +float2 LineHitBox(float3 lineStart, float3 lineEnd, float3 boxMin, float3 boxMax) +{ + float3 invDirection = 1.0f / (lineEnd - lineStart); + float3 enterIntersection = (boxMin - lineStart) * invDirection; + float3 exitIntersection = (boxMax - lineStart) * invDirection; + float3 minIntersections = min(enterIntersection, exitIntersection); + float3 maxIntersections = max(enterIntersection, exitIntersection); + float2 intersections; + intersections.x = max(minIntersections.x, max(minIntersections.y, minIntersections.z)); + intersections.y = min(maxIntersections.x, min(maxIntersections.y, maxIntersections.z)); + return saturate(intersections); +} + #endif