The final code then turns out to be the following:
public static bool RayCast(Ray ray, Polygon polygon, float tmax, out float t, out Vector2 pt, out Vector2 normal)
{
t = float.MaxValue;
pt = ray.Origin;
normal = ray.Direction;
// temp holder for segment distance
float distance;
int crossings = 0;
for (int j = polygon.NumVertices - 1, i = 0; i < polygon.NumVertices; j = i, i++)
{
if (RayIntersectsSegment(ray, polygon.v[j], polygon.v[i], float.MaxValue, out distance))
{
crossings++;
if (distance < t && distance <= tmax)
{
t = distance;
pt = ray.GetPoint(t);
Vector2 edge = polygon.v[j] - polygon.v[i];
normal = Vector2.Normalize(RightPerp(edge));
// no reflection here
}
}
}
return crossings > 0 && crossings % 2 == 0;
}
No comments:
Post a Comment