Given a ray (r0, r1) and a line segment (a, b), I need to calculate the normal of the line segment based on the direction of the ray. For example, in the following picture:
The correct normal given the ray (from picture) and segment should be normal n1. Here is the algorithm I am using to calculate the point of intersection:
public static Vector2? lineSegmentIntersection(Vector2 r0, Vector2 r1, Vector2 a, Vector2 b)
{
Vector2 s1, s2;
s1 = r1 - r0;
s2 = b - a;
float s, t;
s = (-s1.Y * (r0.X - a.X) + s1.X * (r0.Y - a.Y)) / (-s2.X * s1.Y + s1.X * s2.Y);
t = (s2.X * (r0.Y - a.Y) - s2.Y * (r0.X - a.X)) / (-s2.X * s1.Y + s1.X * s2.Y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
{
// Collision detected
// Return the point of intersection
return new Vector2(r0.X + (t * s1.X), r0.Y + (t * s1.Y));
}
return null; // No collision
}
Ideally, I would like to modify this algorithm to calculate the proper normal. Further, I know how to calculate the normals n0 and n1:
norm0 = new Vector2((b.Y - a.Y), -(b.X - a.X));
norm1 = new Vector2(-(b.Y - a.Y), (b.X - a.X));
What do I do next to determine which of those two normals to choose? I get the feeling this is fairly simple and I've been looking at it for too long...