我正在通过编程我的第一个游戏(一个简单的激光镜式游戏)来学习JavaScript。游戏在网格中运行,我想确定一个小区是否有障碍物。所以我称这个函数为:
function updateGrid () {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
//grid[i][j].obstacle = false;
}
}
for (let m = mirrors.length - 1; m >= 0; m--) {
if (grid[i][j].x + cellOffset.x== mirrors[m].x && grid[i][j].y + cellOffset.y == mirrors[m].y) {
grid[i][j].mirror = true;
} else {
grid[i][j].mirror = false;
}
}
if (grid[i][j].x + cellOffset.x == target.x && grid[i][j].y + cellOffset.y == target.y) {
grid[i][j].target = true;
} else {
grid[i][j].target = false;
}
if (grid[i][j].x == laserPen.x && grid[i][j].y + (rowH / 2) - (cellOffset.y / 4) == laserPen.y) {
grid[i][j].pen = true;
} else {
grid[i][j].pen = false;
}
}
}
}
然而,确定单元格是否包含障碍物的if语句似乎不起作用。
这有效(将 grid [i] [j] .obstacle 设置为 true ):
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
//grid[i][j].obstacle = false;
}
}
这不会(将 grid [i] [j] .obstacle 设置为 false ):
for (let o = 0; o < obstacles.length; o++) {
if (grid[i][j].x === obstacles[o].x && grid[i][j].y === obstacles[o].y) {
grid[i][j].obstacle = true;
} else if (grid[i][j].x != obstacles[o].x && grid[i][j].y != obstacles[o].y) {
grid[i][j].obstacle = false;
}
}
我实际上添加了else-if只是为了安全,但它也无法使用简单的else语句。
我正在使用p5.js库,我们将非常感谢您对此处发生的事情的任何见解。谢谢!
答案 0 :(得分:0)
经过一些测试后发现了这个bug。我正在迭代同一网格单元上的所有障碍物(即网格[2] [2]的测试障碍物[0],网格[2] [2]的测试障碍物[1])。这意味着如果阵列中的第一个障碍被证明是真的,但其他障碍被证明是错误的,那么整个网格[2] [2]。障碍就会变得虚假。或者直观地映射:
grid[2][1] ...
grid[2][2].obstacle = true!
grid[2][2].obstacle = false.
grid[2][2].obstacle = false.
grid[2][3] ...
输出:
grid[2][2].obstacle is false :(