当我对角移动时,移动速度变得更快,我知道为什么会发生这种情况,只是不知道如何解决。
function love.update(dt)
if love.keyboard.isDown("w") then player.y = player.y - 75 * dt
end
if love.keyboard.isDown("s") then player.y = player.y + 75 * dt
end
if love.keyboard.isDown("d") then player.x = player.x + 75 * dt
end
if love.keyboard.isDown("a") then player.x = player.x - 75 * dt
end
end
解决方案在于一些简单的向量数学。让我们计算一下按下的键要移入的目录:
local d = {x = 0, y = 0} -- direction to move in
if love.keyboard.isDown("w") then d.y = d.y - 1 end
if love.keyboard.isDown("s") then d.y = d.y + 1 end
if love.keyboard.isDown("d") then d.x = d.x + 1 end
if love.keyboard.isDown("a") then d.x = d.x - 1 end
现在,您可能会得到像
{x = 1, y = 1}
这样的对角线方向。这个向量的长度是多少?根据毕达哥拉斯定理,它是 sqrt(1² + 1²) = sqrt(2),大约为 1.4,而不是 1。如果“直线”前进,则只会得到 1。因此,如果沿对角线走。
我们可以通过“归一化”方向向量来解决这个问题:保持方向,但将幅度设置为 1。为此,如果长度大于 0,我们只需将其除以长度(否则,只需将其保持为0 - 在这种情况下玩家根本没有移动):
local length = math.sqrt(d.x^2 + d.y^2)
if length > 0 then
d.x = d.x / length
d.y = d.y / length
end
现在只需以所需的速度缩放它,然后应用它:
local speed = 75
player.x = player.x + speed * d.x
player.y = player.y + speed * d.y