city-generation/Game/Assets/Scripts/Utils/Algorithms.cs

50 lines
1.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
2015-06-10 08:49:43 +00:00
using TransportGame.Model;
namespace TransportGame.Utils
{
public static class Algorithmss
{
2015-06-10 08:49:43 +00:00
public static bool DoPolygonsIntersect(Vector2[] a, Vector2[] b)
{
foreach (var poly in new[] {a, b})
{
for (int i = 0; i < poly.Length; i++)
{
int j = (i + 1) % poly.Length;
var normal = new Vector2(poly[j].Y - poly[i].Y, poly[i].X - poly[j].X);
double? minA = null, maxA = null;
foreach (var p in a)
{
var projected = Vector2.Dot(normal, p);
if (minA == null || projected < minA)
minA = projected;
if (maxA == null || projected > maxA)
maxA = projected;
}
double? minB = null, maxB = null;
foreach (var p in b)
{
var projected = Vector2.Dot(normal, p);
if (minB == null || projected < minB)
minB = projected;
if (maxB == null || projected > maxB)
maxB = projected;
}
if (maxA <= minB || maxB <= minA)
return false;
}
}
return true;
}
}
}