- Home /
Question by
Artpen · Jul 04, 2021 at 12:59 PM ·
c#mathvector2intersection
Intersection of two lines
Hi guys , I found a code how to find an intersection point of two lines . I do understand how to find intersection x and y using simultaneous equations. But having hard time understanding the code. Need a little help, so I am not just copying it.
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LineSegmentsIntersection
{
public static class Math2d
{
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;
}
}
}
Comment
Looks like the code is checking if lines are parallel or not. Seems like slopes to me but not exactly.
What are var d? var u? and var v?
Thank you