我正在使用带有Löve2D框架的lua和他包含的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
位置是否在0
0.5
范围内。 当然,您需要进行实验,看看什么是好的 epsilon 值。 我只是随意挑选0.5
.