Created
April 8, 2020 07:26
-
-
Save Qu3tzal/68cb08bf712693109726a259d80ddd6d to your computer and use it in GitHub Desktop.
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 <SFML/Graphics.hpp> | |
#include <cmath> | |
// Program parameters. | |
const float TICK_PER_SEC = 60.f; | |
const float MAX_JERK_LENGTH = 100.f; | |
// Computed constants. | |
const sf::Time TICK_TIME = sf::seconds(1.f / TICK_PER_SEC); | |
class Player | |
{ | |
public: | |
explicit Player() | |
: position {0.f, 0.f} | |
, velocity {0.f, 0.f} | |
, acceleration {0.f, 0.f} | |
, jerk {0.f, 0.f} | |
{ | |
shape.setFillColor(sf::Color::Red); | |
shape.setSize({20.f, 20.f}); | |
} | |
void update(const sf::Time &dt) | |
{ | |
// Reset jerk. | |
jerk = {0.f, 0.f}; | |
// Reset player ? | |
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) | |
{ | |
position = velocity = acceleration = {0.f, 0.f}; | |
} | |
// Input reading. | |
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) | |
{ | |
jerk.x += 1.f; | |
} | |
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) | |
{ | |
jerk.x -= 1.f; | |
} | |
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) | |
{ | |
jerk.y -= 1.f; | |
} | |
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) | |
{ | |
jerk.y += 1.f; | |
} | |
// Normalize jerk and multiply by max jerk length. | |
float jerkLength = std::sqrt(std::pow(jerk.x, 2.f) + std::pow(jerk.y, 2.f)); | |
if (std::fabs(jerkLength) > std::numeric_limits<float>::epsilon()) | |
{ | |
jerk *= MAX_JERK_LENGTH / jerkLength; | |
} | |
// Integration. | |
acceleration += jerk * dt.asSeconds(); | |
velocity += acceleration * dt.asSeconds(); | |
position += velocity * dt.asSeconds(); | |
// Update shape. | |
shape.setPosition(position); | |
} | |
void render(sf::RenderWindow &window) const | |
{ | |
window.draw(shape); | |
} | |
private: | |
sf::Vector2f position, velocity, acceleration, jerk; | |
sf::RectangleShape shape; | |
}; | |
int main() | |
{ | |
sf::RenderWindow window {sf::VideoMode {1280, 720}, "Jerk"}; | |
auto view = window.getView(); | |
view.setCenter(0, 0); | |
window.setView(view); | |
Player player; | |
sf::Clock clock; | |
sf::Time elapsed {sf::Time::Zero}; | |
while (window.isOpen()) | |
{ | |
elapsed += clock.restart(); | |
sf::Event event; | |
while (window.pollEvent(event)) | |
{ | |
if (event.type == sf::Event::Closed) | |
window.close(); | |
} | |
if (elapsed >= TICK_TIME) | |
{ | |
elapsed -= TICK_TIME; | |
player.update(TICK_TIME); | |
} | |
window.clear(); | |
player.render(window); | |
window.display(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment