using UnityEngine;
using System.Collections;

public static class Helper2D
{
	public static bool LineSegmentsIntersect (Vector2 l1p1, Vector2 l1p2, Vector2 l2p1, Vector2 l2p2)
	{
		Vector2 a = l1p2 - l1p1;
		Vector2 b = l2p1 - l2p2;
		Vector2 c = l1p1 - l2p1;
   
		float alphaNumerator = b.y * c.x - b.x * c.y;
		float alphaDenominator = a.y * b.x - a.x * b.y;
		float betaNumerator = a.x * c.y - a.y * c.x;
		float betaDenominator = a.y * b.x - a.x * b.y;
   
		bool doIntersect = true;
   
		if (alphaDenominator == 0 || betaDenominator == 0) {
			doIntersect = false;
		} else {
       
			if (alphaDenominator > 0) {
				if (alphaNumerator < 0 || alphaNumerator > alphaDenominator) {
					doIntersect = false;
               
				}
			} else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator) {
				doIntersect = false;
			}
       
			if (doIntersect && betaDenominator > 0) {
				if (betaNumerator < 0 || betaNumerator > betaDenominator) {
					doIntersect = false;
				}
			} else if (betaNumerator > 0 || betaNumerator < betaDenominator) {
				doIntersect = false;
			}
		}
 
		return doIntersect;
	}

	public static Vector2? LinesIntersectionPoint (Vector2 l1p1, Vector2 l1p2, Vector2 l2p1, Vector2 l2p2)
	{
		//Line1
		float A1 = l1p2.y - l1p1.y;
		float B1 = l1p2.x - l1p1.x;
		float C1 = A1 * l1p1.x + B1 * l1p1.y;

		//Line2
		float A2 = l2p2.y - l2p1.y;
		float B2 = l2p2.x - l2p1.x;
		float C2 = A2 * l2p1.x + B2 * l2p1.y;

		float det = A1 * B2 - A2 * B1;
		if (det == 0) {
			return null;//parallel lines
		} else {
			float x = (B2 * C1 - B1 * C2) / det;
			float y = (A1 * C2 - A2 * C1) / det;
			return new Vector2 (x, y);
		}
	}
}
