首页 > 解决方案 > 计算枢轴点周围的 x 和 y 坐标

问题描述

我有一个女孩角色,站在(在这个例子中)x:500 和 y:200。

在此处输入图像描述

在我的 Javascript 游戏中,我需要将另一个角色路由到她左侧 100 像素以内。然而,女孩角色可能站在房间的角落。在这种情况下,我需要计算下一个 x 和 y 坐标是什么,如果我们从站在 x:500 和 y:200 处的女孩向下旋转 20 度,但距离女孩角色仍有 100 像素。

这种计算的名称是什么?

标签: javascriptmathgeometryrotation

解决方案


你想要的是极坐标(半径和角度)。x, y和之间的转换radius, angle是使用完成的

r = sqrt(x^2, y^2)
a = atan(y,x)
x = cos(a)*r
y = sin(a)*r

下面的算法从女孩的位置开始,减去极坐标,看看能不能返回。否则,增加 20 度并继续。

function to_polar(x, y) {
  return [Math.sqrt(x * x + y * y), Math.atan2(y, x)]
}

function from_polar(r, a) {
  return [Math.cos(a) * r, Math.sin(a) * r]
}

function get_other(girl) {
  let r = 100

  for (let degree = 0; degree < 360; degree += 20) {
    let mod = from_polar(r, degree * 180 / Math.PI)
    let other = [girl[0] - mod[0], girl[1] - mod[1]]
    if (is_not_inside_of_wall(other)) {
      return other
    }
  }
  console.log("couldn't find any position :(")
}

let girl = [500, 200]
let other = get_other(girl)
console.log(other)

get_other[ 400, 200 ]在第一次迭代时正确返回


推荐阅读