【问题标题】:Return coordinates (x,y) from an array of numbers in Javascript从Javascript中的数字数组返回坐标(x,y)
【发布时间】:2022-01-24 02:42:40
【问题描述】:

我正在尝试在 Javascript 的 2d 自上而下视图游戏中制作碰撞地图。我正在使用 Tiled 来构建地图。 Tiled 生成一个 json / javascript 文件,其中包含我地图中每个元素的数组。我可以为每个图块设置一个布尔值,因此具有 true 设置的那些将在数组中显示为 1,而具有 false 值的将返回 0。

现在我想将这些数据输出为 x,y 坐标。我的意思是如果我有数组 [0,0,0,0] 我希望那些输出像 (x,y) (0,0), (1,0), (2,0), (3,0)基于 tilemap 数组的宽度和高度。像这样的:

"data":[0,0,0,0,
        1,1,1,1,
        0,0,0,0,
        0,0,0,0]
"height":4,
"width":4,
"x":0,
"y":0

我的问题是我不知道如何对我的循环说它将有四列和四行并且索引应该从 (0,0), (0,1), (0,2) , (0,3) to (1,0), (1,1),(1,2),(1,3) 结束后第一行一直持续到最后一列。

有什么想法吗?

【问题讨论】:

  • 嵌套循环?目前尚不清楚具体问题是什么。

标签: javascript arrays


【解决方案1】:

您可以分别对当前的rowcol 使用两个for 循环:

const tiledOutputJson = {
    "data": [
        0, 0, 0, 0,
        1, 1, 1, 1,
        0, 0, 0, 0,
        0, 0, 0, 0
    ],
    "height": 4,
    "width": 4,
    "x": 0,
    "y": 0
};

const { data, height, width, x, y } = tiledOutputJson;

for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
        console.log(`(${row}, ${col}) = ${data[row * height + col]}`);
    }
    console.log();
}

【讨论】:

  • 我已经考虑了好几个小时,却不知道我可以使用嵌套循环来做到这一点。感谢您的帮助!
【解决方案2】:

一般来说,我建议将其设为 x 的数组,其中包含 y 的数组

[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
]

你可以像这样进行映射

const data = {
  "data": [0, 0, 0, 0,
    1, 1, 1, 1,
    0, 0, 0, 0,
    0, 0, 0, 0
  ],
  "height": 4,
  "width": 4,
  "x": 0,
  "y": 0
}

for (let x = 0; x < data.height * data.width; x = x + data.width) {
  for (let y = x; y < data.width + x; y++) {
    console.log({
      x: x / data.height,
      y: y % data.width,
      v: data.data[y]
    })
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    相关资源
    最近更新 更多