从角度和距离获取X,Y坐标(使用Math.cos()和Math.sin()的值不正确)

时间:2018-12-21 04:29:06

标签: javascript math coordinates

我已经阅读了有关该主题的所有可接受的答案,并准确地重复了其中使用的逻辑,但是我的结果似乎偏斜且“随机”。

我已经正确地从中心对象收集了X,Y和度,如下所示:

console.log('deg' + degrees + ' - ' + 'x' + parseInt(x) + ', y' + parseInt(y));

enter image description here 注意: X,Y网格在显示的视口之外更远。从技术上讲,网格大小不受限制。在此网格空间中,我们处于特定的X,Y坐标中。

现在我要计算一个X,Y坐标,该坐标距单击位置1000像素。这是我要实现的示例:

enter image description here

我在其他地方发现的逻辑应该很简单:

x = 1000 * Math.cos(degrees);
y = 1000 * Math.sin(degrees);
console.log('deg' + degrees + ' - ' + 'x' + parseInt(x) + ', y' + parseInt(y));

结果如下:

enter image description here

问题:在上图中,X,Y坐标明显偏离了我的预期。它们太低了,经常更改为随机数。

此布局的网格如下所示:

enter image description here

注意:X轴向左偏正。这是根本问题,还是我原来的逻辑错了?

感谢您考虑我的问题


我尝试了建议的代码。这是我的结果。

@MBo的现在很旧的答案的结果:

new_x = 1000 * Math.cos(degrees * Math.PI / 180);
new_y = 1000 * Math.sin(degrees * Math.PI / 180);

enter image description here

结果看起来更整洁,“随机性”更小,但是X,Y末端的方向和距离不正确

1 个答案:

答案 0 :(得分:2)

  
    

并且经常更改

  

三角函数使用with radians而不是度,所以计算这样的参数:

 Math.cos(degrees * Math.PI / 180);
 Math.sin(degrees * Math.PI / 180);

要绕某个点旋转,请将这些值添加到其坐标

 x = center_object_x + Math.cos(degrees * Math.PI / 180);
 y = center_object_y + Math.sin(degrees * Math.PI / 180);