我正在嘗試使用 Javascript 在 2d 自上而下的視圖游戲中制作碰撞貼圖。我正在使用 Tiled 來構建地圖。Tiled 生成一個 json/javascript 檔案,其中包含我地圖中每個元素的陣列。我可以為每個 tile 設定一個布林值,因此那些設定為 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) 到 (1,0), (1,1),(1,2),(1,3) 結束后第一行繼續直到最后一列。
任何的想法?
uj5u.com熱心網友回復:
您可以分別為當前row和使用兩個 for 回圈col:
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();
}
uj5u.com熱心網友回復:
一般來說,我建議將其設為 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]
})
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390686.html
標籤:javascript 数组
上一篇:用二維np.zeros()陣列替換熊貓資料框列中的空值
下一篇:錯誤:LoadError:MethodError:沒有方法匹配Array(::Type{Int8},::Int64,::Int64,::Int64)
