-
-
Save anonymous/92fc02ad0e1aff55deb9682244c1f6c1 to your computer and use it in GitHub Desktop.
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 "Game.h" | |
// Split constructor (let it call initialize and load) | |
Game::Game(unsigned int width, unsigned int height, std::string windowTitle) | |
{ | |
// Set the width, height, & title | |
this->width = width; | |
this->height = height; | |
this->windowTitle = windowTitle; | |
// Create the window | |
window.create(sf::VideoMode(width, height), windowTitle); | |
// Frame stuff | |
window.setFramerateLimit(0); | |
window.setVerticalSyncEnabled(true); | |
// Misc | |
window.setMouseCursorVisible(true); | |
this->initialize(); | |
this->loadContent(); | |
} | |
void Game::initialize() | |
{ | |
timePerTick = sf::seconds(1.0f / 60.0f); | |
timeSinceLastUpdate = sf::Time::Zero; | |
frameTime = sf::Time::Zero; | |
} | |
void Game::loadContent() | |
{ | |
// Get fonts | |
robotoFont.loadFromFile("Fonts/Roboto.ttf"); | |
// Set FPS text | |
fps.setFont(robotoFont); | |
fps.setCharacterSize(16); | |
fps.setPosition(10.0f, 10.0f); | |
// Load the player class | |
player.create("Sprites/Skeleton.png", 4, 9, sf::Vector2f(100, 100)); | |
} | |
/*\ //******************************************* | |
|*| | |
|*| GAME LOOP | |
|*| - run() Handles events | |
|*| - update() Handles game updates | |
|*| - draw() Renders everything | |
|*| | |
\*/ //******************************************* | |
void Game::run() | |
{ | |
while (window.isOpen()) | |
{ | |
// Create event | |
sf::Event event; | |
// Handle events | |
while (window.pollEvent(event)) | |
{ | |
if (event.type == sf::Event::Closed) | |
window.close(); | |
} | |
// Exit game | |
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) | |
window.close(); | |
// Updates | |
update(); | |
} | |
} | |
void Game::update() | |
{ | |
// Get the time since this method was last called | |
frameTime = clock.restart(); | |
timeSinceLastUpdate += frameTime; | |
// Update per tick (around 60 ticks per second) | |
while (timeSinceLastUpdate > timePerTick) | |
{ | |
timeSinceLastUpdate -= timePerTick; | |
// Update player | |
player.update(timePerTick.asSeconds()); | |
} | |
// Update FPS | |
fps.setString("FPS: " + std::to_string((int)(1.0f / frameTime.asSeconds()))); | |
// Draw | |
draw(); | |
} | |
void Game::draw() | |
{ | |
// Time between each tick | |
const float alpha = timeSinceLastUpdate / timePerTick; | |
// Draw everything | |
window.clear(); | |
window.draw(fps); | |
player.draw(window, alpha); | |
window.display(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment