pocket-physics
Version:
Verlet physics extracted from pocket-ces demos
109 lines (108 loc) • 2.8 kB
JavaScript
export function v2(x, y) {
return { x: x || 0, y: y || 0 };
}
export const copy = (out, a) => {
out.x = a.x;
out.y = a.y;
return out;
};
export const set = (out, x, y) => {
out.x = x;
out.y = y;
return out;
};
export const add = (out, a, b) => {
out.x = (a.x + b.x);
out.y = (a.y + b.y);
return out;
};
export const sub = (out, a, b) => {
out.x = (a.x - b.x);
out.y = (a.y - b.y);
return out;
};
export const dot = (a, b) => a.x * b.x + a.y * b.y;
export const scale = (out, a, factor) => {
out.x = (a.x * factor);
out.y = (a.y * factor);
return out;
};
export const distance = (v1, v2) => {
const x = v1.x - v2.x;
const y = v1.y - v2.y;
return Math.sqrt(x * x + y * y);
};
export const distance2 = (v1, v2) => {
const x = v1.x - v2.x;
const y = v1.y - v2.y;
return x * x + y * y;
};
export const magnitude = (v1) => {
const x = v1.x;
const y = v1.y;
return Math.sqrt(x * x + y * y);
};
export const normalize = (out, a) => {
const x = a.x;
const y = a.y;
let len = x * x + y * y;
if (len > 0) {
len = 1 / Math.sqrt(len);
out.x = (a.x * len);
out.y = (a.y * len);
}
return out;
};
/**
* Compute the normal pointing away perpendicular from two vectors.
* Given v1(0,0) -> v2(10, 0), the normal will be (0, 1)
* */
export const normal = (out, v1, v2) => {
out.y = (v2.x - v1.x);
out.x = (v1.y - v2.y);
return normalize(out, out);
};
// the perpendicular dot product, also known as "cross" elsewhere
// http://stackoverflow.com/a/243977/169491
export const perpDot = (v1, v2) => {
return v1.x * v2.y - v1.y * v2.x;
};
/**
* This is mostly useful for moving a verlet-style [current, previous]
* by the same amount, translating them while preserving velocity.
* @param by the vector to add to each subsequent vector
* @param vN any number of vectors to translate
*/
export const translate = (by, ...vN) => {
for (let i = 0; i < vN.length; i++) {
const v = vN[i];
add(v, v, by);
}
};
/**
*
* @param v Print this vector for nice logs
*/
export function vd(v) {
return `(${v.x}, ${v.y})`;
}
/**
* Rotate a vector around another point. Taken nearly verbatim from gl-matrix
*/
export const rotate2d = (out, target, origin, rad) => {
//Translate point to the origin
const p0 = target.x - origin.x;
const p1 = target.y - origin.y;
const sinC = Math.sin(rad);
const cosC = Math.cos(rad);
//perform rotation and translate to correct position
out.x = p0 * cosC - p1 * sinC + origin.x;
out.y = p0 * sinC + p1 * cosC + origin.y;
return out;
};
/**
* Compute the Theta angle between a vector and the origin.
*/
export function angleOf(v) {
return Math.atan2(v.y, v.x);
}