RayCapsule.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Geometry/RayCylinder.h>
  6. #include <Jolt/Geometry/RaySphere.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Tests a ray starting at inRayOrigin and extending infinitely in inRayDirection
  9. /// against a capsule centered around the origin with its axis along the Y axis and half height specified.
  10. /// @return FLT_MAX if there is no intersection, otherwise the fraction along the ray.
  11. /// @param inRayDirection Ray direction. Does not need to be normalized.
  12. /// @param inRayOrigin Origin of the ray. If the ray starts inside the capsule, the returned fraction will be 0.
  13. /// @param inCapsuleHalfHeight Distance from the origin to the center of the top sphere (or that of the bottom)
  14. /// @param inCapsuleRadius Radius of the top/bottom sphere
  15. JPH_INLINE float RayCapsule(Vec3Arg inRayOrigin, Vec3Arg inRayDirection, float inCapsuleHalfHeight, float inCapsuleRadius)
  16. {
  17. // Test infinite cylinder
  18. float cylinder = RayCylinder(inRayOrigin, inRayDirection, inCapsuleRadius);
  19. if (cylinder == FLT_MAX)
  20. return FLT_MAX;
  21. // If this hit is in the finite cylinder we have our fraction
  22. if (abs(inRayOrigin.GetY() + cylinder * inRayDirection.GetY()) <= inCapsuleHalfHeight)
  23. return cylinder;
  24. // Test upper and lower sphere
  25. Vec3 sphere_center(0, inCapsuleHalfHeight, 0);
  26. float upper = RaySphere(inRayOrigin, inRayDirection, sphere_center, inCapsuleRadius);
  27. float lower = RaySphere(inRayOrigin, inRayDirection, -sphere_center, inCapsuleRadius);
  28. return min(upper, lower);
  29. }
  30. JPH_NAMESPACE_END