javascript - 计算枢轴点周围的 x 和 y 坐标
问题描述
我有一个女孩角色,站在(在这个例子中)x:500 和 y:200。
在我的 Javascript 游戏中,我需要将另一个角色路由到她左侧 100 像素以内。然而,女孩角色可能站在房间的角落。在这种情况下,我需要计算下一个 x 和 y 坐标是什么,如果我们从站在 x:500 和 y:200 处的女孩向下旋转 20 度,但距离女孩角色仍有 100 像素。
这种计算的名称是什么?
解决方案
你想要的是极坐标(半径和角度)。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 ]
在第一次迭代时正确返回
推荐阅读
- regex - RegEx 用于匹配逗号前的单词,但有例外
- c# - 将 Xamarin.Forms 从 2.xx 升级到 3.xx 时出错
- sql - 在 OVER 子句中使用 ORDER BY
- r - 是否有用于取消哈希数据的 R 函数(相当于 Python 中的“hashlib”函数)?
- javascript - ReplaceWith() 添加新行但不删除旧行?
- python - 如何使用 AdaBoost 和 GridSearchCV 获得最佳估计器参数
- c# - 如何对我的列表进行排序
按日期时间? - postgresql - 增加查询参数直到达到 LIMIT
- java - 我如何告诉 *early* 堆栈帧在一系列递归结束时实现了“成功”?
- jquery - Dropzone maxFilesize 上的错误