Skip to content

Instantly share code, notes, and snippets.

@naezith
Last active September 1, 2019 01:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save naezith/70248aa555ddf87651df to your computer and use it in GitHub Desktop.
Save naezith/70248aa555ddf87651df to your computer and use it in GitHub Desktop.
Minimal SFML and Interpolation example
#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