我正在使用 Lua 重新创建 Pacman 夫人,最近才了解到一系列瓷砖用于碰撞和移动;我正在尝试重新创建它。这是瓷砖地图:
nodemap = {
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,1},
{1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1,1},
{1,1,0,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1},
{1,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1},
{1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1},
{1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1},
{1,1,1,1,0,1,1,1,1,1,0,1,1,1,0,0,1,1,1,0,1,1,1,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1,1,1},
{1,1,1,1,0,1,1,0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从瓷砖跳到瓷砖,再到瓷砖......所以我有这个代码来“顺利”移动 Pacman:
-- Make Pacmans position consist of a single decimal (because over time a number of 1.899999994 will occur and that's ugly)
mrspacman.x = math.floor(mrspacman.x*10)/10
mrspacman.y = math.floor(mrspacman.y*10)/10
--If an arrowkey was pressed (Think of this as "A new direction was queued")
if (mrspacman.nextDirection) then
-- If Pacman is in the center of a tile, then
if (mrspacman.x == math.floor(mrspacman.x)) and (mrspacman.y == math.floor(mrspacman.y)) then
-- If the tile in front of Pacman is empty, set direction to that
if (nodemap[mrspacman.y-math2.sin(mrspacman.dir)][mrspacman.x+math2.cos(mrspacman.dir)]~=1) then
mrspacman.dz = mrspacman.dir
-- Disable this queue
mrspacman.nextDirection = false
end
end
end
-- If Pacman is NOT in the center of a tile
if (mrspacman.x ~= math.floor(mrspacman.x)) or (mrspacman.y ~= math.floor(mrspacman.y)) then
-- Constantly move forwards
mrspacman.x = mrspacman.x + (math2.cos(mrspacman.dz)*mrspacman.speed)
mrspacman.y = mrspacman.y - (math2.sin(mrspacman.dz)*mrspacman.speed)
else
-- If the tile in front of Pacman is empty, move to that tile
if (nodemap[mrspacman.y-math2.sin(mrspacman.dz)][mrspacman.x+math2.cos(mrspacman.dz)] ~= 1) then
mrspacman.x = mrspacman.x + (math2.cos(mrspacman.dz)*mrspacman.speed)
mrspacman.y = mrspacman.y - (math2.sin(mrspacman.dz)*mrspacman.speed)
end
end
mrspacman.dz = 所面对的角度。
mrspacman.dir = 记录的按键。
mrspacman.speed = .1(允许平滑移动的小数)。
执行此代码会导致 Pacman 在按下后退键时冻结,并且在拐角处旋转时其位置变得混乱,穿过墙壁......可以在这里看到。
如何解决这个问题?
更新
我添加了一个名为 math2 的表,由 cos 和 sin fx 组成(只会返回 4 个基本方向的值):
math2 = {
cos = function(angle)
vectors = {1,0,-1,0}
return vectors[(angle/90)+1]
end,
sin = function(angle)
vectors = {0,1,0,-1}
return vectors[(angle/90)+1]
end
}