Game-Timing

Hi everyone,

is this the right approach to limit the game-timming. It works, but sometimes a sprite is not smooth in movement ( a little time).

some pseudo-Code:

lastGameTime=newGameTime;

RenderAllGameGfx();
UpdateAllGameObjects(); // playerX += dt * speedX;

newGameTime=SDL_GetTicks();
dt = (newGameTime-lastGameTime) / (1000.0/60.0);

On creating the SDL_Renderer I donA’t have set the SDL_RENDERERPREVENT_VSYNC flag.

I am grateful for any comment.

Thanks
Alex :slight_smile:

Looks correct to me, except that when you’re calculating the deltatime, you’re dividing 1000.0 with 60.0, which I’m not sure why you do.

Example code on how I usually do it:

#include "SDL.h"

#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
#define PLAYER_WIDTH 32
#define PLAYER_HEIGHT 32

// Double for extra precision
double OldTime = 0.0;
double NewTime = 0.0;
double DeltaTime = 0.0;

// Floats for smooth movement
float PlayerPosX = (WINDOW_WIDTH / 2) - (PLAYER_WIDTH / 2)
float PlayerPosY = (WINDOW_HEIGHT / 2) - (PLAYER_HEIGHT / 2)

float SpeedX = 100.0f;
float SpeedY = 100.0f;

bool Running = true;

SDL_Rect PlayerRect = {(int)PlayerPosX, (int)PlayerPosY, PLAYER_WIDTH, PLAYER_HEIGHT};

SDL_Event Event;

int main(int argc, char* argv[])
{
	// Initialize SDL and such

	while(Running)
	{
		while(SDL_PollEvent(&Event))
		{
			switch(Event.type)
			{
			case SDL_QUIT:
				{
					Running = false;

					break;
				}

			case SDL_KEYDOWN:
				{
					if(Event.key.keysym.sym == SDL_SCANCODE_UP)
						PlayerPosY -= SpeedY * DeltaTime;

					else if(Event.key.keysym.sym == SDL_SCANCODE_DOWN)
						PlayerPosY += SpeedY * DeltaTime;

					if(Event.key.keysym.sym == SDL_SCANCODE_LEFT)
						PlayerPosX -= SpeedX * DeltaTime;

					else if(Event.key.keysym.sym == SDL_SCANCODE_RIGHT)
						PlayerPosX += SpeedX * DeltaTime;
					
					break;
				}
			}

			default:
				break;
		}

		// Calculate the deltatime
		m_NewTime		= SDL_GetTicks();
		m_DeltaTime		= (m_NewTime - m_OldTime) / 1000.0;
		m_OldTime		= m_NewTime;

		// Typecast into int's to get rid of decimal values
		PlayerRect.x = (int)PlayerPosX;
		PlayerRect.y = (int)PlayerPosY;
	}

	// Quit SDL and such

	return 0;
}