Acceleration with dt

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
icekiller8002
Prole
Posts: 49
Joined: Mon Jun 06, 2016 9:28 pm
Location: United States

Acceleration with dt

Post by icekiller8002 »

Hi there, I am trying to make a jumping movement with delta time (compatible with any framerate). Unfortunately, I am struggling to accomplish this. The original code that is not compatible with dt is below:

Code: Select all

-- jumping
if player.jumping then
  -- prevents legs from moving whilst jumping
  if player.frame ~= 0 or player.aTimer ~= 0 then
    player.frame = 0
    player.aTimer = 0
    legsQuad:setViewport(60*player.frame,player.legY,60,15,legs:getDimensions())
  end

  if not player.falling then
    if player.acceleration >= 15 then
      player.falling = true
    else
      player.y = player.y - (15 - player.acceleration)
      player.acceleration = player.acceleration + 1
    end

    if not player.soundPlayed then
      playSound("jump")
      player.soundPlayed = true
    end
  end
end
Any help or direction to making this code dt-compatible would be appreciated.

Code: Select all

function love.draw()
  love.graphics.print("obey")
end
User avatar
ivan
Party member
Posts: 1915
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: Acceleration with dt

Post by ivan »

There is a difference between velocity and acceleration. Generally speaking the formula is
change in position = velocity*dt
With jumping you want to set the velocity once and let the body fall due to gravity.
https://2dengine.com/?p=platformers
User avatar
pgimeno
Party member
Posts: 3672
Joined: Sun Oct 18, 2015 2:58 pm

Re: Acceleration with dt

Post by pgimeno »

The simplest integrator uses these formulas:

velocity = velocity + acceleration * dt
position = position + velocity * dt
mxmlnbndsmnn
Prole
Posts: 37
Joined: Mon Feb 11, 2019 4:17 pm

Re: Acceleration with dt

Post by mxmlnbndsmnn »

For a simple acceleration mechanic I used something like this:

Code: Select all

player.body.x = player.body.x + player.body.velocity.x * dt
player.body.y = player.body.y + player.body.velocity.y * dt
... for the actual movement where velocity.x and .y are equal to the current speed in these directions. And

Code: Select all

player.body.velocity.x = acc.x * targetSpeed.x + (1-acc.x) * player.body.velocity.x
with an acc value between 0 and 1 (in fact, less than 0.1). The target speed is something like the current maximum speed that the player wants to reach. This value can be changed, say depending on the ground the player is standing on, or if he is currently in the air. (Do the same for the y acceleration in case you have a top down view on the player)
Post Reply

Who is online

Users browsing this forum: No registered users and 10 guests