如何验证玩家是否能够跳跃?

我正在使用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

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

点赞
用户2516674
用户2516674

正如Bartek所说,你不应该写y==0,因为y是一个浮点变量,它大概率不会完全等于0,尤其是在物理引擎中。

可以使用一个epsilon值,像这样:

x,y = player.body:getLinearVelocity()
epsilon = 0.5 -- 将其设置为合适的值
if math.abs(y) < epsilon then cantJump = false else cantJump = true end

这意味着“如果玩家的y位置与0之间的差小于0.5,则cantJump = true。” 当然,你需要实验来确定一个好的epsilon值。我只是随便选择了0.5

2015-02-02 19:52:16