如果您需要2D (z=0) 和3D 支持,您可以使用Dot product
const dot = (p1, p2) => p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;
使用平方幅度 (magSq),我们可以计算幅度:mag = Math.sqrt(magSq)
const magSq = ({x, y, z}) => x ** 2 + y ** 2 + z ** 2;
const mag = Math.sqrt(magSq(p));
现在我们可以计算Dot product 并在之后“标准化”它。
现在使用acos() 获取角度:
const angle = Math.acos(dot(p1, p2) / Math.sqrt(magSq(p1) * magSq(p2)));
我们也可以使用Math.hypot(),这是mag的专用JS函数:
const mag = (p) => Math.hypot(p.x, p.y, p.z);
… 并获得角度:
const angle = Math.acos(dot(p1, p2) / (mag(p1) * mag(p2)));
示例:
let a = {x: 0, y: -6, z: 0};
let b = {x: 5, y: 2, z: 0}; // set z != 0 for 3D
let dot = (p1, p2)=> p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;
let magSq = ({x, y, z}) => x ** 2 + y ** 2 + z ** 2;
let angle1 = Math.acos(dot(a, b) / Math.sqrt(magSq(a) * magSq(b)));
console.log('1. Angle:', angle1); // 1.9513027
// ... or
let mag = ({x, y, z}) => Math.hypot(x, y, z);
let angle2 = Math.acos(dot(a, b) / (mag(a) * mag(b)))
console.log('2. Angle:', angle2); // 1.9513027