Last active
September 1, 2019 01:23
-
-
Save naezith/70248aa555ddf87651df to your computer and use it in GitHub Desktop.
Minimal SFML and Interpolation example
This file contains 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 <SFML/Graphics.hpp> | |
#include <chrono> | |
using namespace std::chrono_literals; | |
int main() { | |
sf::RenderWindow window(sf::VideoMode(1280, 720), "Stutter"); | |
sf::Event event; | |
const float dt = 0.008f; | |
std::chrono::nanoseconds timestep(8ms), lag(0ns); | |
auto time_start = std::chrono::high_resolution_clock::now(); | |
sf::RectangleShape rect(sf::Vector2f(5.0f, 720.0f)); | |
float pos = 0.0f, prev_pos = 0.0f, org_pos = 0.0f; | |
while(window.isOpen()) { | |
// Calculate the elapsed time and add it to lag | |
auto now = std::chrono::high_resolution_clock::now(); | |
lag += now - time_start; | |
time_start = now; | |
while(lag >= timestep) { | |
lag -= timestep; | |
// Save the previous value | |
prev_pos = pos; | |
// Poll Events | |
while(window.pollEvent(event)) if(event.type == sf::Event::Closed) window.close(); | |
// Update | |
if((pos += 1000.0f*dt) > 1280.0f) { prev_pos = org_pos = pos = 0.0f; } | |
} | |
// Save the original value before drawing | |
org_pos = pos; | |
// Interpolate | |
pos = prev_pos + (static_cast<double>(lag.count()) / timestep.count()) * (pos - prev_pos); | |
// Set position to interpolated position | |
rect.setPosition(pos, 0.0f); | |
// Render | |
window.clear(); | |
window.draw(rect); | |
window.display(); | |
// Recover the original value | |
pos = org_pos; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment