using dt in external functions

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
1u4
Prole
Posts: 16
Joined: Tue May 01, 2012 6:27 am
Location: Oh no, not Finland!

using dt in external functions

Post 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.
There is a story of a farmer whose horse ran away. That evening the neighbors gathered to commiserate with him since this was such bad luck.
He said, "May be." Continued...
User avatar
Zilarrezko
Party member
Posts: 345
Joined: Mon Dec 10, 2012 5:50 am
Location: Oregon

Re: using dt in external functions

Post 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.
sphyrth
Party member
Posts: 260
Joined: Mon Jul 07, 2014 11:04 am
Contact:

Re: using dt in external functions

Post 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
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Bing [Bot] and 6 guests