找到两个向量之间的角度并检查差异是否在 45 度之间

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

我在屏幕中间有一个物体,其视野为 90 度。它不断围绕原点旋转每一帧。

有一个带有随机 (x,y) 向量的目标对象。我希望这个目标对象在屏幕中心对象的视野内时变为红色。

如果你看到上图,目标在视野内,那么它必须改为红色。但不幸的是我无法做到这一点。

我已经尝试了两个公式来实现这一点:

1. Finding the arccos of the angle
θ = cos-1 [ (a. b) / (|a| |b|) ]

2. Finding the atang of the angle:
θ = atan2(a.y - b.y, a.x - b.x)

这是数字 1 的代码:

let dotProduct = p5.Vector.dot(target, centerView)
let productMag = target.mag() * centerView.mag();
let result = dotProduct / productMag;
let angleInRad = acos(result);
if (angleInRad > HALF_FOV) {
  // Change target color to red
  fill(color(255, 0, 0))
}

这是数字 2 的代码:

let diff = p5.Vector.sub(target, centerView);
let theta = atan2(diff.y, diff.x)
let result = theta
if (result < HALF_FOV && result > HALF_FOV * -1) {
  // Change target color to red
  fill(color(255, 0, 0))
}

当我运行这些代码时,目标变成红色,但当它在视野内时它永远不会改变。

您可以检查并运行我当前的代码 (p5.js) here.

有什么想法吗?谢谢

------更新------

感谢@MBo 告诉我如何解决这个问题。 这里是工作示例,如果有人想检查

javascript math trigonometry
1个回答
0
投票

OK,发现错误——你错误地混合了点和向量。工作变体:

 let targetvec = createVector(width - width / 4 - origin.x, height / 2 - origin.y)
  let centerViewvec = createVector(centerView.x - origin.x, centerView.y - origin.y)
  
   let dotProduct = p5.Vector.dot(targetvec, centerViewvec)
   let productMag = targetvec.mag() * centerViewvec.mag();
   let result = dotProduct / productMag;
   let angleInRad = acos(result);
  //  console.log(angleInRad)
   if (angleInRad < HALF_FOV) {
       fill(color(255, 0, 0))
   }

请注意,如果您经常使用方向,最好存储单位方向向量。

© www.soinside.com 2019 - 2024. All rights reserved.