SDL - Moving character?

Started by
9 comments, last by Muffin 20 years ago
You''re moving your player the amount of ms since you last moved it so that means your player moves at a rate of 1 pixel every millisecond which is far too fast. What you need to do is scale the time since the player last moved and use that to move the player. The simplest way to do this would to be simply divide diff by some factor say 50. 1000 / 50 = 20 so your player would move 20 pixels a second (which is probably too slow). However a problem arises when your frames are drawn quickly. If diff is something like 2 if you divide that by 50 you''ll end up with 0 as they are integer numbers. Even if they were floats and you got the correct results you still have to specify the players position in pixels and you can''t specify positions in fractions of pixels.

So one thing you could do is have a variable that you add diff to every time. When this variable goes over a certain value (we will use 50 again) you divide the variable by 50 to get the amount of pixels to move and then set the variable to the modulos(*) of it''s old value and 50. Here''s an example of how this would all work.

	DWORD t;	t = timeGetTime();	unsigned long diff = 0;	unsigned int counter = 0;	while(!done)    {		while(SDL_PollEvent(&event))        {.................................. and so on .....			if(keys[SDLK_RIGHT])			{				counter += diff;				if(counter >= 50)				{					if(Player.GetX()+1 <= (MAPWIDTH - 1))					{												Player.SetCharacterPosition(Player.GetY(), Player.GetX()+(counter / 50));						if(Player.GetX() > (SQUAREVIEWX + 14))						{								SQUAREVIEWX += 15;						}					}					counter = counter % 50;				}				DrawMap(SQUAREVIEWY, SQUAREVIEWX);				diff = (timeGetTime()-t);				t = timeGetTime();				DrawPlayer(Player.GetY(), Player.GetX());				SDL_Flip(screen);


*When you divide two integers you can only get a whole value, so if you divide say 10 / 3 you''ll get 3, but there''s 1 remainder. The modulos operator % will give the remainder instead of the result so 10 % 3 = 1. This is useful in your case because say the counter value was 98, if you just moved by counter / 50 it''d move 1 and then set counter to 0, the next frame the player may not move again when really it should (because it was almost a move of 2 pixels). So you do count = 98 % 50 and get 48. If this wasn''t done the player may seem to move at a variable jerky speed.

This topic is closed to new replies.

Advertisement