Skip to content

Instantly share code, notes, and snippets.

@sokuhatiku
Created April 4, 2020 09:07
Show Gist options
  • Save sokuhatiku/5ca3d36a2fdda6fd15092792fb67536e to your computer and use it in GitHub Desktop.
Save sokuhatiku/5ca3d36a2fdda6fd15092792fb67536e to your computer and use it in GitHub Desktop.
float3 RaycastSphere(float3 origin, float3 direction, out float hit)
{
float radius = _HoleRadius;
float3 holeOrigin = _HoleOffset;
float3 toCenter = holeOrigin - origin;
if (SqrLength(toCenter) <= pow(radius, 2))
{
hit = 1;
return origin;
}
else
{
if (dot(direction, toCenter) <= 0)
{
hit = -1;
return origin;
}
float a = SqrLength(direction);
float b = dot(holeOrigin - origin, direction);
float c = SqrLength(holeOrigin - origin) - pow(radius, 2);
float ddt = pow(b, 2) - a * c;
if (ddt < 0)
{
hit = -1;
return origin;
}
float dt = sqrt(ddt);
float t = (b - dt) / a;
hit = 1;
float3 hitPosition = origin + direction * t;
return hitPosition;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment