#include "Game.h"
Game::Game() : _Window(sf::VideoMode(640, 480), "Window"), _Player()
{
_Window.setFramerateLimit(60);
_Player.setRadius(20.f);
_Player.setPosition(100.f, 100.f);
_Player.setFillColor(sf::Color::Blue);
Test.setRadius(20.f);
Test.setPosition(50.f, 50.f);
Test.setFillColor(sf::Color::Green);
}
void Game::run()
{
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (_Window.isOpen())
{
//Handle Events
processEvents();
elapsed_time = clock.restart();
elapsed_time += remainder_time;
while (elapsed_time >= timestep)
{
//Game Logic
update(timestep);
elapsed_time -= timestep;
}
remainder_time = elapsed_time;
updateStatistics(timestep);
//Draw to Screen
render();
}
}
void Game::processEvents()
{
sf::Event event;
while (_Window.pollEvent(event))
{ //Event Switch
switch (event.type)
{
//Close Window
case sf::Event::Closed:
_Window.close();
break;
//Key Pressed
case sf::Event::KeyPressed:
handlePlayerInput(event.key.code, true);
break;
//Key Released
case sf::Event::KeyReleased:
handlePlayerInput(event.key.code, false);
break;
}
}
}
void Game::update(sf::Time deltaTime)
{
auto distance_to_move_this_frame = velocity * deltaTime.asSeconds();
sf::Vector2f type_of_movement(0.f, 10.f * deltaTime.asSeconds());
sf::Vector2f movement(0.f, 0.f);
if (_IsMovingUp)
movement.y -= velocity;
if (_IsMovingDown)
movement.y += velocity;
if (_IsMovingLeft)
movement.x -= velocity;
if (_IsMovingRight)
movement.x += velocity;
Test.move(type_of_movement);
_Player.move(movement * deltaTime.asSeconds());
}
void Game::render()
{
_Window.clear();
_Window.draw(_Player);
_Window.draw(Test);
_Window.display();
}
void Game::handlePlayerInput(sf::Keyboard::Key key, bool isPressed)
{
if (key == sf::Keyboard::W)
{
_IsMovingUp = isPressed;
}
if (key == sf::Keyboard::S)
{
_IsMovingDown = isPressed;
}
if (key == sf::Keyboard::A)
{
_IsMovingLeft = isPressed;
}
if (key == sf::Keyboard::D)
{
_IsMovingRight = isPressed;
}
}
void Game::updateStatistics(sf::Time timestep)
{
_StatisticsUpdateTime += timestep;
_StatisticsNumFrames += 1;
if (_StatisticsUpdateTime >= sf::seconds(1.0f))
{
system("CLS");
cout << "Frames / Second = " << _StatisticsNumFrames << endl;
cout << "Time / Update = " << (_StatisticsUpdateTime.asMicroseconds() / _StatisticsNumFrames) << endl;
_StatisticsUpdateTime -= sf::seconds(1.0f);
_StatisticsNumFrames = 0;
}
}