Browse Source

Particle Physics: framerate and deltatime

Godzil 1 year ago
parent
commit
c517f6eb5d
4 changed files with 34 additions and 4 deletions
  1. 1 1
      CMakeLists.txt
  2. 16 3
      source/app.cpp
  3. 1 0
      source/include/app.h
  4. 16 0
      source/include/physics/constants.h

+ 1 - 1
CMakeLists.txt

@@ -16,7 +16,7 @@ set(CMAKE_CXX_STANDARD 17)
 set(CMAKE_CXX_STANDARD_REQUIRED ON)
 set(CMAKE_CXX_EXTENSIONS OFF)
 
-set(COMP_FLAGS "-Wall -Wextra -Wno-unused-parameter -Wno-unused-result -Wno-write-strings")
+set(COMP_FLAGS "-Wall -Wextra")
 
 if (WARN_AS_ERROR)
     set(COMP_FLAGS "${COMP_FLAGS} -Werror")

+ 16 - 3
source/app.cpp

@@ -12,6 +12,8 @@
 #include <imgui_sdl.h>
 #include <imgui_impl_sdl.h>
 
+#include <physics/constants.h>
+
 void application::parseParameters(int argc, char *argv[])
 {
     // Nothing to do for now
@@ -20,7 +22,7 @@ void application::parseParameters(int argc, char *argv[])
 void application::setup()
 {
     this->running = graphics::openWindow();
-
+    this->millisecsPreviousFrame = SDL_GetTicks();
     this->part = new particle(50, 100, 1.0);
 }
 
@@ -50,9 +52,20 @@ void application::input()
 
 void application::update()
 {
-    this->part->velocity = vec2(2, 0);
+    /* Let's make sure we are running at the expected framerate */
+    uint32_t now = SDL_GetTicks();
+    int32_t timeToWait = MILLISECS_PER_FRAME - (now - this->millisecsPreviousFrame);
+    if (timeToWait > 0) // && timeToWait <= MILLISECS_PER_FRAME)
+    {
+        SDL_Delay(timeToWait);
+    }
+    double deltaTime = (SDL_GetTicks() - this->millisecsPreviousFrame) / 1000.0;
+    this->millisecsPreviousFrame = SDL_GetTicks();
+
+
+    this->part->velocity = vec2(100 *  deltaTime, 30 * deltaTime);
 
-    this->part->position += this->part->velocity;
+    this->part->position += (this->part->velocity);
 }
 
 void application::render()

+ 1 - 0
source/include/app.h

@@ -15,6 +15,7 @@
 class application
 {
 private:
+    uint32_t millisecsPreviousFrame;
     bool running;
     particle *part;
 

+ 16 - 0
source/include/physics/constants.h

@@ -0,0 +1,16 @@
+/*
+ * 2D Physic Engine
+ * constants.h: 
+ * Based on pikuma.com Learn Game Physics Engine Programming course.
+ * Copyright (c) 2022 986-Studio. All rights reserved.
+ *
+ * Created by Manoël Trapier on 08/06/2022.
+ */
+
+#ifndef PHYSICENGINE_CONSTANTS_H
+#define PHYSICENGINE_CONSTANTS_H
+
+const uint32_t FPS = 60;
+const int32_t MILLISECS_PER_FRAME = 1000 / FPS;
+
+#endif /* PHYSICENGINE_CONSTANTS_H */