How to make an object jump only once. in the LÖVE framework?

11

I'm trying to make a game, using the framework LÖVE to Lua , in which the player is a ball and has to overcome obstacles and enemies but I'm having a problem in making the jumps. >

function love.keypressed( key )
    if key == "w" then
        print("Teste")
        objects.ball.body:applyForce(0, -300)
    end
end

When I use this function every time I press w , the "Test" is printed but the ball does not move, another alternative I tried was isDown() but if I kept pressing the ball it would stop the stars. Any alternative / solution?

    
asked by anonymous 04.02.2014 / 21:57

2 answers

3

To check if the ball is in contact with the ground (or whatever) you need to define the callback functions for object collisions

g = true
w = love.physics.newWorld(0, 10, true)
w:setCallbacks(beginContact, endContact, nil, nil) --[[Define o nome da funçao a ser 
executa quando contato é estabelecido entre dois objetos e quando o mesmo termina]]

--Definimos agora a funcao
function beginContact (a, b, ev) --Objeto(fixture) a e b e evento de colisão
  g = true
end

function endContact(a, b, ev) 
  g=false
end

--Modificamos o tratamento de teclas
function love.keypressed( key )
    if key == "w" and g then
        print("Teste")
        objects.ball.body:applyForce(0, -300)
    end
end

In this way, the force will only be applied when g = true (ball in contact with the ground), note that the objects that participated in the collision event were not checked, if there are other objects it will be necessary to implement this verification. >

This implementation can be done using the setUserData () and getUserData () methods of the table returned by love.physics.newFixture ()

bola.fixture:setUserData("Bola")
chao.fixture:setUserData("Chao")
function beginContact (a, b, ev)
   if a:getUserData() == "Bola"and b:getUserData() == "Chao" or 
       a:getUserData() == "Chao" and b:getUserData() == "Bola" then
      g = true
   end
end

Example

    
12.02.2014 / 00:07
6

You should check that the ball is on the ground before applying force. This will prevent the ball from flying infinitely, as it is happening.

For this, you can check if the velocity at y of the ball is zero (ie, the ball is on the ground), before applying force. Must have other better options (do not know much of LÖVE), but should solve. Should be something like:

function love.keypressed( key )
    if key == "w" and objects.ball.y_velocity == 0 then
        print("Teste")
        objects.ball.body:applyForce(0, -300)
    end
end
  • link
  • Note: This solution only resolves to the object walking on flat (zero inclined) platforms. For an inclined plane and that the object slide the previous solution will cause bugs, because the object will be on the ground but will be moving in y. In this case, the solution is to check ground collision instead of comparing speed and zero.

        
    04.02.2014 / 22:47