从 3 个向量中获取角度,不排除钝角的非反射
Getting the angle from 3 vectors, without excluding non-reflex of obtuse angles
所以我这两天苦苦挣扎,找到了很多答案,但我修改了一个
findAngle(c, b, a) {
const ab = {x: b.x - a.x, y: b.y - a.y};
const cb = {x: b.x - c.x, y: b.y - c.y};
const dot = (ab.x * cb.x + ab.y * cb.y); // dot product
const cross = (ab.x * cb.y - ab.y * cb.x); // cross product
let alpha = Math.atan2(cross, dot);
if (alpha < 0) {
alpha = (Math.PI * 2 + alpha);
}
return alpha;
}
我不确定它是否正确,我不喜欢 alpha < 0 部分谁能提出更好的意见
// assuming that b is the point at which you want to find the angle (formed by vectors bc and ba)
const angle = (c, b, a) => {
const bc = {x: c.x - b.x, y: c.y - b.y};
const ba = {x: a.x - b.x, y: a.y - b.y};
// the cosine of the angle between the two vectors is their dot product divided by the product of their magnitudes
const cos = (bc.x * ba.x + bc.y * ba.y) / (Math.hypot(bc.x, bc.y) * Math.hypot(ba.x, ba.y));
// return the angle in degrees
return 180 * Math.acos(cos) / Math.PI;
}
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: -3, y: -4})); // the angle between two opposite vectors
console.log(angle({x: 0, y: 4}, {x: 0, y: 0}, {x: 4, y: 0})); // the angle between two perpendicular vectors
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: 4, y: 3}));
所以我这两天苦苦挣扎,找到了很多答案,但我修改了一个
findAngle(c, b, a) {
const ab = {x: b.x - a.x, y: b.y - a.y};
const cb = {x: b.x - c.x, y: b.y - c.y};
const dot = (ab.x * cb.x + ab.y * cb.y); // dot product
const cross = (ab.x * cb.y - ab.y * cb.x); // cross product
let alpha = Math.atan2(cross, dot);
if (alpha < 0) {
alpha = (Math.PI * 2 + alpha);
}
return alpha;
}
我不确定它是否正确,我不喜欢 alpha < 0 部分谁能提出更好的意见
// assuming that b is the point at which you want to find the angle (formed by vectors bc and ba)
const angle = (c, b, a) => {
const bc = {x: c.x - b.x, y: c.y - b.y};
const ba = {x: a.x - b.x, y: a.y - b.y};
// the cosine of the angle between the two vectors is their dot product divided by the product of their magnitudes
const cos = (bc.x * ba.x + bc.y * ba.y) / (Math.hypot(bc.x, bc.y) * Math.hypot(ba.x, ba.y));
// return the angle in degrees
return 180 * Math.acos(cos) / Math.PI;
}
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: -3, y: -4})); // the angle between two opposite vectors
console.log(angle({x: 0, y: 4}, {x: 0, y: 0}, {x: 4, y: 0})); // the angle between two perpendicular vectors
console.log(angle({x: 3, y: 4}, {x: 0, y: 0}, {x: 4, y: 3}));