Last active
December 18, 2015 00:09
-
-
Save loganwm/5695033 to your computer and use it in GitHub Desktop.
Kayne, this is an example of delta_time in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <chrono> | |
#include <thread> | |
#include <cmath> | |
#define TIME_WASTE_MAGIC_NUMBER 5000000 | |
using std::chrono::duration_cast; | |
using std::chrono::milliseconds; | |
using std::chrono::monotonic_clock; | |
float entity_position; /* used to represent the position of some test entity in space */ | |
void one_of_your_entities_to_update(float delta_time); /* used to represent an update method for a test entity */ | |
int main(int argc, char** argv) | |
{ | |
//steady_clock for GCC 4.7+ | |
auto current_frame = monotonic_clock::now(); | |
auto last_frame = monotonic_clock::now(); | |
while (true) | |
{ | |
last_frame = current_frame; | |
current_frame = monotonic_clock::now(); | |
/* while the duration cast should yield whole numbers there are benefits to casting to float fraction of a second in terms of explaining motion */ | |
float delta_time = (duration_cast<milliseconds>(current_frame - last_frame).count() / 1000.0f); | |
std::cout << "Time spent in last frame: " << delta_time << std::endl; | |
/* now here's where we would run any and all updates */ | |
one_of_your_entities_to_update(delta_time); | |
std::cout << "The entity is currently at x = " << entity_position << std::endl; | |
/* waste time */ | |
for (int i = 0; i < TIME_WASTE_MAGIC_NUMBER; i++) | |
{ | |
sqrt(i); | |
} | |
} | |
} | |
void one_of_your_entities_to_update(float delta_time) | |
{ | |
constexpr float speed = 1; /* units per second */ | |
entity_position += (delta_time * speed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've done this already, I don't need this.