How to delta time properly?

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
Posts: 21
Joined: Mon Jan 07, 2019 12:38 pm

How to delta time properly?

Post by milkbomb11 » Sun Feb 17, 2019 2:12 pm

I've got this code which controls a top-down shooter player's movement

Code: Select all

function player.move(speed, friction, dt)
  if love.keyboard.isDown("a") then
    player.xv = player.xv - speed*dt
  elseif love.keyboard.isDown("d") then
    player.xv = player.xv + speed*dt

  if love.keyboard.isDown("w") then
    player.yv = player.yv - speed*dt
  elseif love.keyboard.isDown("s") then
    player.yv = player.yv + speed*dt

  player.x = player.x + player.xv*dt
  player.y = player.y + player.yv*dt
  player.xv = player.xv * friction
  player.yv = player.yv * friction
Do I have to multiply dt at the last two lines too?
And when do I have to multiply stuff with dt and when do have to not?

Posts: 4
Joined: Sat Mar 11, 2017 4:31 pm

Re: How to delta time properly?

Post by Rucoon » Sun Feb 17, 2019 2:22 pm

Yes, you will want to use dt on friction too. If you don't then (lets say your game is running at 60 fps) player.xv and player.yv will be multiplied by friction 60 times a second when you only want it to be multiplied by the total of friction once a second. Delta time is the time between two frames so it will only use a part of friction each frame this code is called. Really any time you have something happen over a space of time you will want to use dt. (This can be slowly changing something like you are doing here, or a timer to have something happen.) You will also need to up the value of friction to get what you are looking for after changing this. The fps of a game can change a lot so you don't want to ever rely on it.

User avatar
Posts: 73
Joined: Fri Nov 16, 2012 9:34 pm

Re: How to delta time properly?

Post by keharriso » Sun Feb 17, 2019 4:57 pm

Correct me if I'm wrong, but wouldn't one of the simple friction equations be:

Code: Select all

player.xv = player.xv - friction * player.xv * dt
player.yv = player.yv - friction * player.yv * dt
Also, very nit-picky, but what you call "speed" seems to be acceleration.
LÖVE-Nuklear - a lightweight immediate mode GUI for LÖVE games

User avatar
Party member
Posts: 1547
Joined: Fri Mar 07, 2008 1:39 pm

Re: How to delta time properly?

Post by ivan » Sun Feb 17, 2019 6:10 pm

For "damping", I recommend the Box2D formula:

Code: Select all

velocity = velocity / (1 + damping*dt)
Where the damping coefficient is usually between 0-1
(it could be greater than 1 but then the movement looks float-y).
Further reading:

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests