Page 1 of 1
using dt in external functions
Posted: Sat Sep 13, 2014 5:25 am
by 1u4
Hi, In player.lua, I have
Code: Select all
function player_move()
if love.keyboard.isDown("left") then
player.x = player.x - (player.speed * dt)
end
if love.keyboard.isDown("right") then
player.x = player.x + (player.speed * dt)
end
end
In main.lua, I have
Code: Select all
function love.update(dt)
player_move()
end
Which returns the error, dt has a null value (or similar). How can I apply delta time when using functions outside of main?
Thanks.
Re: using dt in external functions
Posted: Sat Sep 13, 2014 5:39 am
by Zilarrezko
Simple fix. You have to pass dt into the player_move function. Like so...
Code: Select all
function player_move(dt) --Notice I put it as a parameter here
if love.keyboard.isDown("left") then
player.x = player.x - (player.speed * dt)
end
if love.keyboard.isDown("right") then
player.x = player.x + (player.speed * dt)
end
end
Code: Select all
function love.update(dt)
player_move(dt) --And then passed love.update's dt parameter to player_move's parameter
end
It will work then.
The reason you have to do that is because when a parameter is passed into a function, it creates a local variable that is used inside that function. So to pass that local variable to another function, you give that function the variable as a parameter when calling that function. So that way that function can then use it. If you have any other questions man, just ask.
Re: using dt in external functions
Posted: Sat Sep 13, 2014 6:56 am
by sphyrth
Another possible solution is you use the love.timer.getDelta() function for getting the DeltaTime if you prefer it.
Code: Select all
function player_move()
dt = love.timer.getDelta()
if love.keyboard.isDown("left") then
player.x = player.x - (player.speed * dt)
end
if love.keyboard.isDown("right") then
player.x = player.x + (player.speed * dt)
end
end