For loop Lua for loops(Love2d)有问题
虽然我读过一些关于Lua的教程,并且我脑子里有一个关于如何使用Lua的for循环的想法,但我遇到了麻烦。也许是因为我习惯了Python的for循环?每当玩家在我的游戏中移动时,游戏会检查地图上是否有墙挡住了去路,并检查NPC是否在目标坐标中 虽然我让墙检查功能完美,但这个新的NPC for loop让玩家永远不会移动。checkSpace函数查看当前只有一个NPC的列表,查看玩家是否可以移动到目的地For loop Lua for loops(Love2d)有问题,for-loop,lua,love2d,For Loop,Lua,Love2d,虽然我读过一些关于Lua的教程,并且我脑子里有一个关于如何使用Lua的for循环的想法,但我遇到了麻烦。也许是因为我习惯了Python的for循环?每当玩家在我的游戏中移动时,游戏会检查地图上是否有墙挡住了去路,并检查NPC是否在目标坐标中 虽然我让墙检查功能完美,但这个新的NPC for loop让玩家永远不会移动。checkSpace函数查看当前只有一个NPC的列表,查看玩家是否可以移动到目的地 player = { grid_x = 2, grid_y = 2, a
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 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
我已经在这个位置发布了完整的代码:我假定您的意思是您在这方面遇到了问题:
for _,v in pairs(npcs) do
if grid_x == v.grid_x and grid_y == v.grid_y then
return true
end
end
NPC在哪里
npcs = {npc}
这是一个包含一个项目的表格,即npc,它本身就是
npc = {
grid_x = 4,
grid_y = 3,
act_x = 64,
act_y = 48,
}
因此for循环只涉及一对一次迭代,其密钥被丢弃,其值为npc,因此grid_x==v.grid_x和grid_y==v.grid_y将npc的grid x和y与给定给checkSpace的值进行比较,只有当它们匹配时才返回true。带有循环的npcs={npc}是奇数,但我假设这是因为您发布了最少的示例。到目前为止还不错,没什么问题
但是,checkSpace会将玩家的当前位置与正在循环的npc的位置进行比较,而您应该检查的是npc是否位于建议的目的地:
if grid_x + direction[1] == v.grid_x and grid_y + direction[2] == v.grid_y then
从你的帖子中很难说这是否会解决你的问题,因为我不认为你提到的症状checkSpace总是返回true是正确的,但是循环是正确的,谓词是错误的,应该像我上面展示的那样 你怎么知道checkSpace总是返回true?你通过方向来调整x和y位置以进行墙检查,而不是NPC检查,这是故意的吗?@Moop我的程序的工作方式是,每当我尝试移动玩家时,程序都会检查目标方块中是否有墙或NPC。如果有墙或NPC,则玩家不会移动。程序的运行方式就像每个checkSpace都返回true一样。我拿出脚本中的NPC检查部分,只使用墙检查运行,效果很好,所以我猜问题出在NPC检查部分。至于检查NPC和墙的x和y坐标,这是因为墙的最低x和y坐标为1,而玩家的x和y坐标为0。你有程序的所有代码吗?您发布的代码中似乎没有任何错误。我将其发布在此处:我进行了更改,但正如预期的那样,主要问题仍然存在。基本上,每当玩家点击方向键时,玩家角色都会朝该方向行走。如果路上有墙或NPC,玩家角色将不会移动。问题是自从我添加了check NPC函数后,玩家就不会移动,这意味着,据我所知,checkSpace函数的NPC部分正在返回True。