Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Sprite moving speed same on all computers  (Read 4830 times)

0 Members and 1 Guest are viewing this topic.

programmer47

  • Newbie
  • *
  • Posts: 12
    • View Profile
Sprite moving speed same on all computers
« on: November 13, 2011, 05:22:47 pm »
I have a player that is moved when the left or right arrows is pressed, and on my computer making him move by 0.5 (pixels?) every update looks OK.  But on other, faster computers there will be faster updates so the player will move faster, and slower on slower computers.  I've tried using a clock and moving the player using this alogarithm:
Code: [Select]
sprite.Move(speed / (1 / clock.GetElapsedTime()));
The clock will measure it in how many seconds it takes for an update to come (let's call it SPF for seconds per frame) so I've converted it to FPS (frames per second) by dividing 1 by it.  I've used this number to divide the speed by so the speed should, by my calculations, be how many pixels it moves every second.  But even having the speed at a high number like 200, the player moves very slowly.  I'm not sure I'm managing the fps very well.  Does anyone know how to make sure the sprite is moving the same speed on all computers?[/code]

luiscubal

  • Jr. Member
  • **
  • Posts: 58
    • View Profile
Sprite moving speed same on all computers
« Reply #1 on: November 13, 2011, 07:46:54 pm »
Aside from the fact that your code won't work on SFML 2, you are over complicating that formula. You can simplify it to be:

Code: [Select]
sprite.Move(speed * clock.GetElapsedTime());
Remember to reset the clock at the end of each frame.

If you follow this formula and use the clock properly, this should ensure the same speed across all computers...

kolofsson

  • Full Member
  • ***
  • Posts: 100
    • View Profile
Sprite moving speed same on all computers
« Reply #2 on: November 14, 2011, 11:07:35 am »
Yes, you are definitely overdoing it, even theoretically, with the seconds-per-frame :D.

By the way, I think the variable that you named "speed" should be called "velocity". Velocity is a vector, it has direction AND value, speed has just a value. Of course, I'm aware you may already know that and use the name "speed" for convenience.

I'm sure you know this equation:

Code: [Select]
average velocity = position change / time change

Since we are looking for position change, we can transform this equation into:

Code: [Select]
position change = velocity * time change
[m] = [m/s] * [s]


To calculate time change, I suggest measuring gaps between each frame.

Code: [Select]
sf::Clock clock;
Uint32 last_frame = clock.GetElapsedTime();

while (game_running)
{
time_diff = clock.GetElapsedTime() - last_frame;
sprite.Move(velocity * time_diff);
}


Remember that time_diff is in milliseconds, so if your velocity is in meters per SECOND, divide time_diff by 1000 so it's in seconds as well.

 

anything