# Collision/Intersection of (2D) Ray to Line Segment

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...

If assume that your code works properly, the easiest solution is to select correct normal from these two ones.

You can do this just by calculating the dot product of the ray vector and the normal. If the result is negative, than this is the normal you are looking for.

For example:

Vector2 ray;
ray = r1 - r0;
float result;
//if result < 0 than the norm0 is the correct normal
result  = ray.X * norm0.X + ray.Y * norm0.Y;


You should be aware, that your code have to handle the case of parallel ray and segment. Code, that you've listed will raise an exception of dividing by zero.