calculate vector collision in csharp

To calculate vector collision in C#, you can use the vector product to determine if two vectors intersect or not. Here is the code snippet for it:

main.cs
public static bool DoLinesIntersect(Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2)
{
    // calculate the direction of each line
    Vector2 dir1 = end1 - start1;
    Vector2 dir2 = end2 - start2;

    // calculate the cross product of the directions
    float cross = dir1.X * dir2.Y - dir1.Y * dir2.X;

    // if the cross product is zero, the lines are parallel and do not intersect
    if (cross == 0f)
    {
        return false;
    }

    // calculate the difference in position of the two start points
    Vector2 diff = start2 - start1;

    // calculate the parameter values for the lines where they intersect
    float t = (diff.X * dir2.Y - diff.Y * dir2.X) / cross;
    float u = (diff.X * dir1.Y - diff.Y * dir1.X) / cross;

    // if both parameters are within 0 and 1, then the lines intersect
    if (t >= 0f && t <= 1f && u >= 0f && u <= 1f)
    {
        return true;
    }

    return false;
}
927 chars
31 lines

This function takes four Vector2 variables: start1, end1, start2, and end2. They represent the two lines you want to check for intersection.

The function calculates the direction of each line, then calculates the cross product of the directions. If the cross product is zero, the lines are parallel and do not intersect. If the cross product is not zero, then the function calculates the parameter values for both lines where they intersect. If both parameter values are within 0 and 1, then the lines intersect.

gistlibby LogSnag