UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

35 lines (26 loc) 897 B
/** * Uses Green's Theorem to compute area of a 2d polygon * @param {number[]|Float32Array|Float64Array} points * @param {number} point_count * @returns {number} */ export function compute_polygon_area_2d(points, point_count) { let sum = 0; for (let i = 0; i < point_count - 1; i++) { const i2 = i * 2; const x0 = points[i2]; const y0 = points[i2 + 1]; const x1 = points[i2 + 2]; const y1 = points[i2 + 3]; sum += x0 * y1 - y0 * x1; } const first_x = points[0]; const first_y = points[1]; const last_x = points[point_count * 2 - 2]; const last_y = points[point_count * 2 - 1]; if (first_x !== last_x || first_y !== last_y) { // doesn't wrap around, let's close the loop ourselves sum += last_x * first_y - last_y * first_x; } return sum * 0.5; }