从3个向量获取角度,不排除钝角的非反射性

问题描述 投票:0回答:1

所以我在过去的两天中苦苦挣扎,找到了很多答案,但我修改了一个答案

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部分,任何人都可以提出更好的意见

javascript math vector angle
1个回答
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}));
© www.soinside.com 2019 - 2024. All rights reserved.