# What is wrong with my deltatime?

I have this simple struct that is supposed to calculate the time difference between 2 frames:

struct Clock
{
public:
Clock() {};
~Clock() {};

double CalculateDifference()
{
previousFrame = currentFrame;
currentFrame = SDL_GetPerformanceCounter();
deltaTime = (double)((currentFrame - previousFrame) * 1000 / SDL_GetPerformanceFrequency());
return deltaTime;
}

private:
uint64_t currentFrame = SDL_GetPerformanceCounter();
uint64_t previousFrame = 0;
double deltaTime = 0.0;
};


This is how I'm using it in my game loop:

DeltaTime = clock.CalculateDifference() * 0.001; // *0.001 to convert from ms to seconds because I heard deltatime should be in seconds...?


then:

velocityY -= 0.02f * m_DeltaTime;
Player.GetPosition().y += velocityY ;


The code above occurs every frame because I am making a simple doodle jump clone wherein the player is constantly jumping from one platform to another. I am using low level OpenGL programming for flexibility and exercise. I nearly got the game done but my timestamps seems messed up as sometimes the player jumps higher in one frame than previous frame...

Thanks!

• Any help please? Jul 2 '17 at 10:26
• You forgot to multiply the velocity by the delta-time? Jul 2 '17 at 10:58

I take it the only issue with your timestep is that it's causing different sized jumps on each frame.

This is because your timestep is completely variable, the velocity that you're multiplying by the time delta is always going to be different because there's nothing to say that the time between each frame is going to be the same.

The code for finding the difference between frames isn't incorrect per-se, it does what you were trying to make it do; it's just the application of the timestep system that requires some revision.

This code is problematic:

Player.GetPosition().y += velocityY;


Adding positions and velocities does not make much sense unless the velocity is multiplied by an amount of time; it’s an indication that you need to use your delta time here:

Player.GetPosition().y += m_DeltaTime * velocityY;


However this still has the problem that m_DeltaTime * velocityY is not exactly the distance traveled during the frame; it would only be the case if velocityY had been constant.

This version is more physically accurate:

double prevVelocityY = velocityY;
velocityY -= 0.02f * m_DeltaTime;
Player.GetPosition().y += 0.5 * (velocityY + prevVelocityY) * m_DeltaTime;