UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

26 lines (18 loc) 667 B
/** * Assuming the input is an N-dimension vector, normalizes the vector to magnitude of 1 * @param {number[]|Float32Array|Float64Array} result * @param {number[]|Float32Array|Float64Array} data * @param {number} [length] number of dimensions */ export function vector_normalize(result, data, length = data.length) { let magnitude2 = 0; for (let i = 0; i < length; i++) { const value = data[i]; const value2 = value * value; magnitude2 += value2; } const magnitude_inv = 1 / Math.sqrt(magnitude2); for (let i = 0; i < length; i++) { result[i] = data[i] * magnitude_inv; } }