c++objectwinapigame-developmentframe-rate

How to control the speed of objects in my simple game


I am making a game like space invaders in c++ using the win32 api. I am a beginner.

When I increase my games FPS, game objects move faster across the screen. I want objects to move the same speed across the screen no matter what the FPS is.

I use the <chrono> and <tread> library to determine how many times the main game loops per second and use sleep_for() to add a delay to meet the desired FPS:

std::this_thread::sleep_for(std::chrono::milliseconds(targetFrameTime - elapsedTime));

I move objects in the main loop like this:

if (userInput.get_right_key_down()) {
     rect_x = rect_x + 5;
}

I would rather not use thread if possible. I don't really understand it and don't know if I need it.


Solution

  • I think the best way is to fix the start time, perform sleep_for for a while, and then perform the movement using the speed factor.

    const auto start = std::chrono::high_resolution_clock::now();
    ...
    std::this_thread::sleep_for(std::chrono::seconds(1));
    

    Move objects in the main loop like this:

    const auto end = std::chrono::high_resolution_clock::now();
    const std::chrono::duration<double> elapsed = end - start;
    double dt = elapsed.count();
    
    ...
    
    if (userInput.get_right_key_down()) {
         rect_x = (int) ((double) rect_x + 5.0 * dt); // 5.0 - is the speed factor px/sec
         // but the best way is to use rect_x as a field with type of double.
         // and convert (trunc) it to the integer only on the render step
         // rect_x = rect_x + 5.0 * dt;
    }