public static void GetInertia(Vector2[] vertices, out float result) { Contract.Requires(vertices != null); Contract.Requires(vertices.Length > 0); if (vertices.Length == 1) { result = 0; return; } float denom = 0; float numer = 0; var v1 = vertices[vertices.Length - 1]; Vector2 v2; for (var index = 0; index < vertices.Length; index++, v1 = v2) { v2 = vertices[index]; float a, b, c, d; Vector2.Dot(ref v2, ref v2, out a); Vector2.Dot(ref v2, ref v1, out b); Vector2.Dot(ref v1, ref v1, out c); Vectors2.ZCross(ref v1, ref v2, out d); d = Math.Abs(d); numer += d; denom += (a + b + c) * d; } result = denom / (numer * 6); }
/// <summary> /// Calculates the area of a polygon. /// </summary> /// <param name="vertices">The vertices of the polygon.</param> /// <param name="result">the area.</param> public static void GetArea(Vector2[] vertices, out float result) { Contract.Requires(vertices != null); Contract.Requires(vertices.Length > 2); float area = 0; var v1 = vertices[vertices.Length - 1]; Vector2 v2; for (var index = 0; index < vertices.Length; ++index, v1 = v2) { v2 = vertices[index]; float temp; Vectors2.ZCross(ref v1, ref v2, out temp); area += temp; } result = Math.Abs(area * .5f); }
/// <summary> Calculates the centroid of a polygon.</summary> /// <param name="vertices">The vertices of the polygon.</param> /// <param name="centroid">The centroid of a polygon.</param> /// <remarks>This is also known as center of gravity/mass.</remarks> public static void GetCentroid(Vector2[] vertices, out Vector2 centroid) { Contract.Requires(vertices != null); Contract.Requires(vertices.Length > 2); centroid = Vector2.Zero; float temp; float area = 0; var v1 = vertices[vertices.Length - 1]; Vector2 v2; for (var index = 0; index < vertices.Length; ++index, v1 = v2) { v2 = vertices[index]; Vectors2.ZCross(ref v1, ref v2, out temp); area += temp; centroid.X += ((v1.X + v2.X) * temp); centroid.Y += ((v1.Y + v2.Y) * temp); } temp = 1 / (Math.Abs(area) * 3); centroid.X *= temp; centroid.Y *= temp; }