Reputation: 41
I'm working on a small game using lua with Löve2D framework and his included binding of Box2D, I'm trying to verify if the player can jump, so I used this code (It's not the entire code, just the essential) :
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
But my problem is that the detection is a little bit random, sometimes the player can jump when he's on the ground or some objects, sometimes he can't. How can I fix it ?
Upvotes: 1
Views: 115
Reputation: 251
As Bartek says, you shouldn't be doing y == 0
because y
is a floating point variable, and it's presumably unlikely that it will be exactly equal to 0, especially in a physics engine.
Use an epsilon value like this:
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
This is saying "cantJump = true
if the player's y
position is within 0.5
of 0
." Of course, you'll want to experiment to see what a good epsilon value is. I just arbitrarily picked 0.5
.
Upvotes: 1