@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
40 lines (33 loc) • 1.15 kB
JavaScript
import { assert } from "../../assert.js";
/**
* Compute average-weighted centroid of a set of 3d vectors
* @param {number[]} out
* @param {number} out_offset where to start writing the result
* @param {number[]} input
* @param {number} input_offset where to start reading
* @param {number} count how many elements to use
* @returns {number[]} same as the `out` parameter, returned for convenience
*/
export function v3_array_centroid(out, out_offset, input, input_offset, count) {
assert.isNonNegativeInteger(out_offset, 'out_offset');
assert.isNonNegativeInteger(input_offset, 'input_offset');
assert.isNonNegativeInteger(count, 'count');
let x = 0;
let y = 0;
let z = 0;
for (let i = 0; i < count; i++) {
const offset = input_offset + i * 3;
x += input[offset];
y += input[offset + 1];
z += input[offset + 2];
}
if (count > 0) { // avoid division by zero
x /= count;
y /= count;
z /= count;
}
out[out_offset] = x;
out[out_offset + 1] = y;
out[out_offset + 2] = z;
return out;
}