Skip to content

Instantly share code, notes, and snippets.

@MalcolmMacDonald
Created February 11, 2022 21:23
Show Gist options
  • Select an option

  • Save MalcolmMacDonald/d0e4c5dd304ec7bba4e4a4f1d7a06688 to your computer and use it in GitHub Desktop.

Select an option

Save MalcolmMacDonald/d0e4c5dd304ec7bba4e4a4f1d7a06688 to your computer and use it in GitHub Desktop.
Line Segment intersection
public static bool IntersectLineSegments(Vector2 a0, Vector2 a1, Vector2 b0, Vector2 b1, out Vector2 intersection)
{
Vector3 X = Vector3.Cross(
Vector3.Cross(((Vector3)a0) + Vector3.forward, ((Vector3)a1) + Vector3.forward),
Vector3.Cross(((Vector3)b0) + Vector3.forward, ((Vector3)b1) + Vector3.forward));
intersection = new Vector2(X.x / X.z, X.y / X.z);
//Lines are not parallel
if (float.IsNaN(intersection.x) || float.IsNaN(intersection.y))
{
return false;
}
// On segment A
float aDist = Vector2.Dot(intersection - a0, (a1 - a0).normalized);
if (aDist <= 0 || aDist >= (a1 - a0).magnitude)
{
return false;
}
// On segment B
float bDist = Vector2.Dot(intersection - b0, (b1 - b0).normalized);
if (bDist <= 0 || bDist >= (b1 - b0).magnitude)
{
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment