I have a library with a lot of duplicate code to accommodate different collection types, and its starting to get a bit tedious, is there a better way to do this to reduce the amount of duplication going on ? Its only going to get worse the more functions i add...
This is my current library script:
using System.Collections.Generic;
using UnityEngine;
namespace Math {
public static class Geometry
{
public static float Area(List<Vector2> points)
{
float a = 0;
for (int i = 0; i < points.Count; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Count];
a += p1.x * p2.y - p2.x * p1.y;
}
return a * 0.5f;
}
public static float Area(List<Vector3> points)
{
float a = 0;
for (int i = 0; i < points.Count; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Count];
a += p1.x * p2.z - p2.x * p1.z;
}
return a * 0.5f;
}
public static float Area(Vector3[] points)
{
float a = 0;
for (int i = 0; i < points.Length; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Length];
a += p1.x * p2.z - p2.x * p1.z;
}
return a * 0.5f;
}
public static float Area(Vector2[] points)
{
float a = 0;
for (int i = 0; i < points.Length; i++)
{
var p1 = points[i];
var p2 = points[(i + 1) % points.Length];
a += p1.x * p2.y - p2.x * p1.y;
}
return a * 0.5f;
}
public static bool IsClockwise(List<Vector3> points)
{
float sum = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.z + point1.z);
}
return sum > 0;
}
public static bool IsClockwise(Vector3[] points)
{
float sum = 0;
for (int i = 0; i < points.Length - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.z + point1.z);
}
return sum > 0;
}
public static bool IsClockwise(List<Vector2> points)
{
float sum = 0;
for (int i = 0; i < points.Count - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.y + point1.y);
}
return sum > 0;
}
public static bool IsClockwise(Vector2[] points)
{
float sum = 0;
for (int i = 0; i < points.Length - 1; i++)
{
var point1 = points[i];
var point2 = points[i + 1];
sum += (point2.x - point1.x) * (point2.y + point1.y);
}
return sum > 0;
}
}
}