【Unity】線分同士の交差判定

実装時に少しはまってしまったので備忘録として残しておきます。
f:id:setchi_q:20170712201930p:plain

実装

(交差判定部分のみ)

public static bool LineSegmentsIntersection(
    Vector2 p1,
    Vector2 p2,
    Vector2 p3,
    Vector2 p4,
    out Vector2 intersection)
{
    intersection = Vector2.zero;

    var d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);

    if (d == 0.0f)
    {
        return false;
    }

    var u = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
    var v = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d;

    if (u < 0.0f || u > 1.0f || v < 0.0f || v > 1.0f)
    {
        return false;
    }

    intersection.x = p1.x + u * (p2.x - p1.x);
    intersection.y = p1.y + u * (p2.y - p1.y);

    return true;
}

動作

f:id:setchi_q:20170712202458g:plain
Gifのように動作するプロジェクト一式を公開しました。
github.com