繁体   English   中英

从 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: cx - bx, y: cy - by}; const ba = {x: ax - bx, y: ay - by}; // 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}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM