• Advertisement
Sign in to follow this  

Unity [SDL] Same Execution Time != PC's

This topic is 3376 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi gamedev community, I need 60 frames per second in my game. Is this code correct???
//
// Game Loop
//

while (!done) {

    //
    // Begin Frame:
    //

    int initialTicks = SDL_GetTicks();

    // Compute Frame
    .
    .
    .
    // End Compute Frame


    //
    // End Frame
    //

    int finalTicks = SDL_GetTicks();

    // 60 frames per second = 1000 miliseconds / 60 = 16,6 miliseconds
    while (finalTicks - initialTicks < 17)
        finalTicks = SDL_GetTicks();
}
I'm executing my game in two PC's with 2 processors and with 1 processors, and the speed isn't the same :( Thanks!

Share this post


Link to post
Share on other sites
Advertisement
The change in the above post should make no difference.

What you're probably finding is that you are simply not managing to get 60 frames per second on one or both machines. That code limits you to 60 frames per second if you would normally run faster, but won't speed you up if you were running slower!

Measure your actual frames per second on each computer and see what you get.

Share this post


Link to post
Share on other sites
With SDL that usually means drawing less, or not using any alpha blending, or both. Or moving to OpenGL for rendering.

Share this post


Link to post
Share on other sites
Thanks for the answers. I found the error. Basically I do this for each frame:
(1) Draw Map
(2) Compute colision
(3) Render Enemies (ship, shots, explosions)
(4) Render player ship (ship, shots, explosions)
(5) Show info (lifes, score, nº level, etc)

(2) to (5): I have developed the code.
(1): I use the SDL_Mappy class to render map.

Then I skipped (1) and I counted 170 fps :)
Maybe I need to write the code to draw the map.

Share this post


Link to post
Share on other sites
First, you need to let the OS breath. You can't just while like that, the CPU will be stuck at 100% usage. I know some PCs *cough*mac book pro*cough* that will simply shutdown after couple minutes. You need a sleep or wait for the SDL paint event.

Then after that, as Kylotan said, you need to compensate if you have less frames available. Rendering is lagging, and you have 30 fps for example, each frame you will need to update twice.


void SDL_Paint_Even()
{
int nbFrameToUpdate = updateTimer(); // In there you check the time elapsed
// between the 2 frames and return the number of frame to update. In a good
// FPS, you will get 0 here often

while (nbFrameToUpdate)
{
UpdateYourGame();
nbFrameToUpdate--;
}

RenderYourGame();
}

Share this post


Link to post
Share on other sites
Quote:
Original post by Daivuk
Then after that, as Kylotan said, you need to compensate if you have less frames available. Rendering is lagging, and you have 30 fps for example, each frame you will need to update twice.

What if you get 45 fps, should you update 1.5 times per frame then? Or update once this frame, and twice the next? I think that might result in very jerky movement.

A better solution would be to calculate seconds per frame instead of frames per seconds, and then multiply that with for example the speed of a ship. Assume for example that you want to move the players ship 20 pixels per second. If it takes 0.1 seconds to draw a frame you get 20 * 0.1 = 2, so you move the ship 2 pixels this frame. With this approach it won't matter how many frames you render per second, the movement will be constant.

Share this post


Link to post
Share on other sites
Peros:
In my example, I'm assuming you are interpolating in the render too. But that works fine anyway without it. it will not look jerky without interpolation.

And I understand your way of doing it, but this breaks the "perfect" simulation. Try to run a physical situation, with your method the simulation will be different every time you run the game.

It's also unfriendly for networked game, for the same reason above: It breaks the simulation.

It also makes collisions more difficult if you have lags.

Share this post


Link to post
Share on other sites
Quote:
And I understand your way of doing it, but this breaks the "perfect" simulation. Try to run a physical situation, with your method the simulation will be different every time you run the game.

Not necessarily.

What Perost mentioned should work the same regardless of frame rate since it performs the physics independent of frame rate. For example, a slower computer should show a falling block in the same place as a faster one after 1 second with the noticeable exception that the slower one will look more jumpy.

One of the problems you may encounter when the time slice of a particular frame exceeds a certain amount is that certain collisions may be missed i.e. objects may appear to pass through another object producing different results on different machines.

This can be worked around by specifying a maximum allowed time slice. If a particular frame takes longer than this maximum, run the physics portion multiple times until it has used the amount of time the frame has taken.

for example:

// the maximum amount of time allowed per physics iteration
const int max_time = 20;

// the amount of time this frame took
int frame_time = 35;

while( frame > 0 )
{
// the time slice to compute physics for
int delta = min(max_time,frame_time);

// do physics stuff based on delta time
physics( delta );

frame_time -= delta;
}


The physics method will run 2 times because the frame took 1.75 times longer than the maximum time. The first iteration will go at the maximum time slice, the second at slightly less. This will help make an object in motion be in the same place on 2 different machines at the same time regardless of computing speed however slower machines will show slower/jumpier movement since the object will most likely travel greater distances per frame.

Other factors affect how accurately something like a physics simulation can be reproduced such as fixed vs floating point math however that is a different topic better left to someone with more math skills than myself and this is a good place to start.

Share this post


Link to post
Share on other sites
Quote:
Original post by evillive2
Quote:
And I understand your way of doing it, but this breaks the "perfect" simulation. Try to run a physical situation, with your method the simulation will be different every time you run the game.

Not necessarily.


Fix Your Timestep! ;)

Share this post


Link to post
Share on other sites
Thanks for info.
Now I'm counting miliseconds per frame and I compute movement in this manner:

//
// (1) I compute miliseconds per frame
//

int msPerFrame = ComputeMsPerFrame();


//
// (2) I move the ship, depending in msPerFrame and ship speed
//
//
// void cShip::moveRight(float units) {
// setXCoord( getXCoord() + (getSpeed() * units));
// }
//
//

myship.moveRight( ((float)msPerFrame) / 1000);


Is this correct to manage execution speed?



Share this post


Link to post
Share on other sites
Yeah, though it's more common to pass the value in as the time in seconds rather than calling it the 'units', and to pass it in as a float or double.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By Vu Chi Thien
      Hi fellow game devs,
      First, I would like to apologize for the wall of text.
      As you may notice I have been digging in vehicle simulation for some times now through my clutch question posts. And thanks to the generous help of you guys, especially @CombatWombat I have finished my clutch model (Really CombatWombat you deserve much more than a post upvote, I would buy you a drink if I could ha ha). 
      Now the final piece in my vehicle physic model is the differential. For now I have an open-differential model working quite well by just outputting torque 50-50 to left and right wheel. Now I would like to implement a Limited Slip Differential. I have very limited knowledge about LSD, and what I know about LSD is through readings on racer.nl documentation, watching Youtube videos, and playing around with games like Assetto Corsa and Project Cars. So this is what I understand so far:
      - The LSD acts like an open-diff when there is no torque from engine applied to the input shaft of the diff. However, in clutch-type LSD there is still an amount of binding between the left and right wheel due to preload spring.
      - When there is torque to the input shaft (on power and off power in 2 ways LSD), in ramp LSD, the ramp will push the clutch patch together, creating binding force. The amount of binding force depends on the amount of clutch patch and ramp angle, so the diff will not completely locked up and there is still difference in wheel speed between left and right wheel, but when the locking force is enough the diff will lock.
      - There also something I'm not sure is the amount of torque ratio based on road resistance torque (rolling resistance I guess)., but since I cannot extract rolling resistance from the tire model I'm using (Unity wheelCollider), I think I would not use this approach. Instead I'm going to use the speed difference in left and right wheel, similar to torsen diff. Below is my rough model with the clutch type LSD:
      speedDiff = leftWheelSpeed - rightWheelSpeed; //torque to differential input shaft. //first treat the diff as an open diff with equal torque to both wheels inputTorque = gearBoxTorque * 0.5f; //then modify torque to each wheel based on wheel speed difference //the difference in torque depends on speed difference, throttleInput (on/off power) //amount of locking force wanted at different amount of speed difference, //and preload force //torque to left wheel leftWheelTorque = inputTorque - (speedDiff * preLoadForce + lockingForce * throttleInput); //torque to right wheel rightWheelTorque = inputTorque + (speedDiff * preLoadForce + lockingForce * throttleInput); I'm putting throttle input in because from what I've read the amount of locking also depends on the amount of throttle input (harder throttle -> higher  torque input -> stronger locking). The model is nowhere near good, so please jump in and correct me.
      Also I have a few questions:
      - In torsen/geared LSD, is it correct that the diff actually never lock but only split torque based on bias ratio, which also based on speed difference between wheels? And does the bias only happen when the speed difference reaches the ratio (say 2:1 or 3:1) and below that it will act like an open diff, which basically like an open diff with an if statement to switch state?
      - Is it correct that the amount of locking force in clutch LSD depends on amount of input torque? If so, what is the threshold of the input torque to "activate" the diff (start splitting torque)? How can I get the amount of torque bias ratio (in wheelTorque = inputTorque * biasRatio) based on the speed difference or rolling resistance at wheel?
      - Is the speed at the input shaft of the diff always equals to the average speed of 2 wheels ie (left + right) / 2?
      Please help me out with this. I haven't found any topic about this yet on gamedev, and this is my final piece of the puzzle. Thank you guys very very much.
    • By Estra
      Memory Trees is a PC game and Life+Farming simulation game. Harvest Moon and Rune Factory , the game will be quite big. I believe that this will take a long time to finish
      Looking for
      Programmer
      1 experience using Unity/C++
      2 have a portfolio of Programmer
      3 like RPG game ( Rune rune factory / zelda series / FF series )
      4 Have responsibility + Time Management
      and friendly easy working with others Programmer willing to use Skype for communication with team please E-mail me if you're interested
      Split %: Revenue share. We can discuss. Fully Funded servers and contents
      and friendly easy working with others willing to use Skype for communication with team please E-mail me if you're interested
      we can talk more detail in Estherfanworld@gmail.com Don't comment here
      Thank you so much for reading
      More about our game
      Memory Trees : forget me not

      Thank you so much for reading
      Ps.Please make sure that you have unity skill and Have responsibility + Time Management,
      because If not it will waste time not one but both of us
       

    • By RoKabium Games
      We've now started desinging the 3rd level of "Something Ate My Alien".
      This world is a gas planet, and all sorts of mayhem will be getting in our aliens way!
      #screenshotsaturday
    • By Pacoquinha Studios
      Kepuh's Island is Multiplayer 3D Survival Game where you survive on the Kepuh's Islands, confronting challenges that are not only other players but also bosses, and even the environment itself.
      We have a lowpoly faster battle-royale idea, where about 12 players on the map fighting for survival! Also adding some more things into that style such as bosses around the map giving you abilities and much more such as vehicles, weapons, skins, etc...
      Now we are on cartase which is a crowdfunding online which purpose is to raise funds for the development of the game. Come and be part of this development.
      Link for Cartase: https://www.catarse.me/kepuhsisland?ref=project_link
      We post updates and trailers on
      Twitter: https://twitter.com/pcqnhastudios
      Facebook: https://www.facebook.com/pacoquinhastudios/
      Site: http://pacoquinhastudios.com.br
      If you could check out it would be great
      Thnks
      Some images:





  • Advertisement