Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active October 5, 2022 21:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unitycoder/8d1c2905f2e9be693c78db7d9d03a102 to your computer and use it in GitHub Desktop.
Save unitycoder/8d1c2905f2e9be693c78db7d9d03a102 to your computer and use it in GitHub Desktop.
RayBoxIntersect Faster than bounds.IntersectRay
// this is faster than unity *.bounds.IntersectRay(ray)
// original source https://gamedev.stackexchange.com/a/103714/73429
float RayBoxIntersect(Vector3 rpos, Vector3 rdir, Vector3 vmin, Vector3 vmax)
{
float t1 = (vmin.x - rpos.x) / rdir.x;
float t2 = (vmax.x - rpos.x) / rdir.x;
float t3 = (vmin.y - rpos.y) / rdir.y;
float t4 = (vmax.y - rpos.y) / rdir.y;
float t5 = (vmin.z - rpos.z) / rdir.z;
float t6 = (vmax.z - rpos.z) / rdir.z;
float aMin = t1 < t2 ? t1 : t2;
float bMin = t3 < t4 ? t3 : t4;
float cMin = t5 < t6 ? t5 : t6;
float aMax = t1 > t2 ? t1 : t2;
float bMax = t3 > t4 ? t3 : t4;
float cMax = t5 > t6 ? t5 : t6;
float fMax = aMin > bMin ? aMin : bMin;
float fMin = aMax < bMax ? aMax : bMax;
float t7 = fMax > cMin ? fMax : cMin;
float t8 = fMin < cMax ? fMin : cMax;
float t9 = (t8 < 0 || t7 > t8) ? -1 : t7;
return t9;
}
// old, using bounds
//if (some.bounds.IntersectRay(ray) == true) {}
// new, using method above
if (RayBoxIntersect(ray.Origin, ray.Direction, some.bounds.min, some.bounds.max) > 0) {}
@unitycoder
Copy link
Author

sometimes bugged?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment