【发布时间】:2014-11-28 00:48:07
【问题描述】:
虽然我已经阅读了一些关于 Lua 的教程,并且我对如何使用 Lua 的 for 循环有了一个想法,但我遇到了麻烦。也许是因为我习惯了 Python 的 for 循环?每当玩家在我的游戏中移动时,游戏都会检查地图上的墙壁是否挡住了路,并检查 NPC 是否在目的地坐标中。
虽然我的墙检查功能完美无缺,但这个新的 NPC for 循环使玩家永远不会移动。 checkSpace 函数通过一个 NPC 列表(目前只有一个)查看玩家是否可以移动到目的地。
player = {
grid_x = 2,
grid_y = 2,
act_x = 32,
act_y = 32,
transit = false,
direction = {0, 0}
}
npc = {
grid_x = 4,
grid_y = 3,
act_x = 64,
act_y = 48,
}
npcs = {npc}
function checkSpace(grid_y, grid_x, direction)
if map[grid_y + (1 + direction[2])][grid_x + (1 + direction[1])] == 0 then
-- if checkNPCs
for _,v in pairs(npcs) do
if grid_x == v.grid_x and grid_y == v.grid_y then
return true
end
end
end
end
function love.keypressed(key)
if player.transit == false then
if key == "up" then
player.direction = {0, -1}
if checkSpace(player.grid_y, player.grid_x, player.direction) == true then
player.grid_y = player.grid_y - 1
-- move player.direction before the if statement to make the player change direction whether or no there is space to move
player.transit = true
end
end
end
end
编辑:我稍微摆弄了一下程序,并且取得了一些进展。与按键程序检查 checkSpace 是否返回 True 不同,程序已被修改,以便在没有障碍时返回 false。
if key == "up" then
player.direction = {0, -1}
if checkSpace(player.grid_y, player.grid_x, player.direction) == false then
player.grid_y = player.grid_y - 1
-- move player.direction before the if statement to make the player change direction whether or no there is space to move
player.transit = true
end
我在我的程序中使用了一个非常基本(实际上没用)的 for 循环,但如果我尝试用它做任何更高级的事情,我会收到我的玩家角色不会移动的错误。
for nameCount = 1, 1 do
if grid_x + direction[1] == npc.grid_x and grid_y + direction[2] == npc.grid_y then
return true
else
return false
end
end
我已经在这个位置发布了完整的代码:http://pastebin.com/QNpAU6yi
【问题讨论】:
-
你怎么知道
checkSpace总是返回true? -
你通过方向调整 x 和 y 位置以进行墙壁检查,但不用于 NPC 检查,这是故意的吗?
-
@Moop 我的程序的工作方式是,当我尝试移动玩家时,程序会检查目标方格中是否有墙或 npc。如果有墙或 NPC,则玩家不会移动。程序的行为方式就像每个 checkSpace 都返回 true。我取出脚本的 NPC 检查部分,只用墙检查运行它,它工作正常,所以我猜问题出在 NPC 检查部分。至于检查 NPC 和墙的 x 和 y 坐标,因为墙可以是最低的 X 和 Y 坐标为 1,而玩家为 0。
-
你有这个程序的所有代码吗?您发布的代码中似乎没有任何内容不正确。
-
我把它贴在这里:pastebin.com/bvwCUauU