Page 1 of 1

Am I using DT correctly?

Posted: Mon Jun 10, 2013 11:20 pm
by CharlieL
I've run into a simple problem that has left me extremely confused.
I program on a mid-range laptop, and frequently send demonstrations of my code to friends whom use higher end PCs. I understand the need for dt in running games identically on devices with different specs, but I think I may have been using it wrong. The code I have pasted below causes the player to jump to its own head height and drop down to the floor again when 'w' is pressed, but on a friend's gaming PC it flies off the screen and takes around 10 seconds to reappear. I'm convinced this is due to me using dt incorrectly.

The code:

Code: Select all

function love.load()
	Player = {}
	Player.X1, Player.Y1 = 100, 100
	Player.W, Player.H = 50, 100
	Player.X2, Player.Y2 = Player.X1 + Player.W
	Player.XSpeed, Player.YSpeed = 0, 0
	Player.Falling = true

	FloorHeight = 480

end

function love.update(dt)
	dt = math.min(dt, 1/60)
	
	-- Updating the player's position and hitbox.
	Player.X2, Player.Y2 = Player.X1 + Player.W, Player.Y1 + Player.H
	Player.X1 = Player.X1 + (Player.XSpeed * dt)
	Player.Y1 = Player.Y1 + (Player.YSpeed * dt)

	-- Check if the player is falling.
	if Player.Y2 > FloorHeight then
		Player.Falling = false
	else
		Player.Falling = true
	end

	-- Falling.
	if Player.Falling == true then
		if Player.YSpeed < 500 then
			Player.YSpeed = Player.YSpeed + 1.5
		end
	else
		Player.YSpeed = 0
	end

	-- Jumping behaviour.
	if love.keyboard.isDown("w") then
		if Player.Falling == false then
			Player.YSpeed = -600
		end
	end

	-- Moving left and right.
	if love.keyboard.isDown("a") then
		Player.XSpeed = -200
	elseif love.keyboard.isDown("d") then
		Player.XSpeed = 200
	else
		Player.XSpeed = 0
	end

end

function love.draw()
	love.graphics.rectangle("fill", Player.X1, Player.Y1, Player.W, Player.H)
	love.graphics.line(0, FloorHeight, 1000, FloorHeight)

	if Player.Falling == false then
		love.graphics.print("falling : FALSE", 10, 25)
	else
		love.graphics.print("falling : TRUE", 10, 25)
	end

end
Thanks for the help guys. This is a really friendly forum.

Re: Am I using DT correctly?

Posted: Mon Jun 10, 2013 11:52 pm
by Jasoco
When you increase the speed variable, you have to also multiply it by dt. Else it adds that amount every frame and on a fast machine it'll speed up a lot faster than it should. Also make sure to limit the max speed else it will fly off super fast like you mentioned.

Re: Am I using DT correctly?

Posted: Tue Jun 11, 2013 12:05 am
by CharlieL
Thanks! It works great now.

<3