Skip to content

Instantly share code, notes, and snippets.

@sinbad
Last active September 30, 2024 18:26
Show Gist options
  • Save sinbad/68cb88e980eeaed0505210d052573724 to your computer and use it in GitHub Desktop.
Save sinbad/68cb88e980eeaed0505210d052573724 to your computer and use it in GitHub Desktop.
Unity 2D Line Segment Intersection
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
using UnityEngine;
public static class LineUtil {
public static void Swap<T>(ref T lhs, ref T rhs) {
T temp = lhs;
lhs = rhs;
rhs = temp;
}
public static bool Approximately(float a, float b, float tolerance = 1e-5f) {
return Mathf.Abs(a - b) <= tolerance;
}
public static float CrossProduct2D(Vector2 a, Vector2 b) {
return a.x * b.y - b.x * a.y;
}
/// <summary>
/// Determine whether 2 lines intersect, and give the intersection point if so.
/// </summary>
/// <param name="p1start">Start point of the first line</param>
/// <param name="p1end">End point of the first line</param>
/// <param name="p2start">Start point of the second line</param>
/// <param name="p2end">End point of the second line</param>
/// <param name="intersection">If there is an intersection, this will be populated with the point</param>
/// <returns>True if the lines intersect, false otherwise.</returns>
public static bool IntersectLineSegments2D(Vector2 p1start, Vector2 p1end, Vector2 p2start, Vector2 p2end,
out Vector2 intersection) {
// Consider:
// p1start = p
// p1end = p + r
// p2start = q
// p2end = q + s
// We want to find the intersection point where :
// p + t*r == q + u*s
// So we need to solve for t and u
var p = p1start;
var r = p1end - p1start;
var q = p2start;
var s = p2end - p2start;
var qminusp = q - p;
float cross_rs = CrossProduct2D(r, s);
if (Approximately(cross_rs, 0f)) {
// Parallel lines
if (Approximately(CrossProduct2D(qminusp, r), 0f)) {
// Co-linear lines, could overlap
float rdotr = Vector2.Dot(r, r);
float sdotr = Vector2.Dot(s, r);
// this means lines are co-linear
// they may or may not be overlapping
float t0 = Vector2.Dot(qminusp, r / rdotr);
float t1 = t0 + sdotr / rdotr;
if (sdotr < 0) {
// lines were facing in different directions so t1 > t0, swap to simplify check
Swap(ref t0, ref t1);
}
if (t0 <= 1 && t1 >= 0) {
// Nice half-way point intersection
float t = Mathf.Lerp(Mathf.Max(0, t0), Mathf.Min(1, t1), 0.5f);
intersection = p + t * r;
return true;
} else {
// Co-linear but disjoint
intersection = Vector2.zero;
return false;
}
} else {
// Just parallel in different places, cannot intersect
intersection = Vector2.zero;
return false;
}
} else {
// Not parallel, calculate t and u
float t = CrossProduct2D(qminusp, s) / cross_rs;
float u = CrossProduct2D(qminusp, r) / cross_rs;
if (t >= 0 && t <= 1 && u >= 0 && u <= 1) {
intersection = p + t * r;
return true;
} else {
// Lines only cross outside segment range
intersection = Vector2.zero;
return false;
}
}
}
}
@shanghalf
Copy link

awesome ! works perfectly thanks for this <3

@Najmul59
Copy link

Verify Github on Galxe. gid:AnLTmP36d5nYvuvt7eimgd

@Najmul59
Copy link

Verify Github on Galxe. gid:AnLTmP36d5nYvuvt7eimgd

@Najmul59
Copy link

Very strong project

@Najmul59
Copy link

Very strong project

Verify Github on Galxe. gid:AnLTmP36d5nYvuvt7eimgd

@adunato
Copy link

adunato commented Feb 27, 2023

This works great and how cool it is to come across the creator of the mighty Ogre3D after all these years :)

@achimmihca
Copy link

achimmihca commented Feb 28, 2023

Please define a license for this (e.g. MIT license).
Great solution!

@sinbad
Copy link
Author

sinbad commented Feb 28, 2023

Public domain, use it however you want (I've added License.txt)

@chris-heathwood
Copy link

chris-heathwood commented May 29, 2024

In my case I actually just needed to know the distance to the intersection with a square which you can do with the Bounds and a Ray. Code snippet below:

Bounds bounds = square.bounds;
Vector2 direction = point - previousPoint;
Ray ray = new(previousPoint, direction);

if (bounds.IntersectRay(ray, out float distance))
{
                    Debug.Log("Collide Distance: " + distance);
}

There is also bounds.Contains(point) which I found useful too.

Just in case it is useful to anyone else 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment