如何验证玩家是否可以跳跃?

How to verify if the player can jump?

我正在使用 lua 和 Löve2D 框架及其包含的 Box2D 绑定开发一个小游戏,我试图验证玩家是否可以跳跃,所以我使用了这段代码(这不是整个代码,只是必要的):

function love.update(dt)
    world:update(dt)
    x,y = player.body:getLinearVelocity()
    if y == 0 then cantJump = false else cantJump = true end

    player.body:setAngle(0)
    player.x = player.body:getX() - 16 ; player.y = player.body:getY() - 16;

    if love.keyboard.isDown("d") then player.body:setX(player.body:getX() + 400*dt) ; player.body:applyForce(0,0) end
    if love.keyboard.isDown("q") then player.body:setX(player.body:getX() - 400*dt) ; player.body:applyForce(0,0) end
    if love.keyboard.isDown(" ") and not cantJump then player.body:setLinearVelocity(0,-347) end
 end

但我的问题是检测有点随机,有时玩家在地面或某些物体上时可以跳跃,有时不能。我该如何解决?

正如 Bartek 所说,你不应该做 y == 0 因为 y 是一个浮点变量,它不太可能完全等于 0,尤其是在物理引擎中.

使用这样的 epsilon 值:

x,y = player.body:getLinearVelocity()
epsilon = 0.5 -- Set this to a suitable value
if math.abs(y) < epsilon then cantJump = false else cantJump = true end

这是说“cantJump = true 如果玩家的 y 位置在 00.5 范围内。”当然,您需要进行试验以了解什么是好的 epsilon 值。我随便选了0.5.