Improved performance of view by only updating when necessary

This commit is contained in:
Maximilian Giller 2023-05-10 11:30:11 +02:00
parent 160a1afd7e
commit 0f0629b291
2 changed files with 36 additions and 13 deletions

View file

@ -1,6 +1,6 @@
#include "world_view.h"
WorldView::WorldView() : view(nullptr)
WorldView::WorldView() : view(nullptr), hasViewChanged(false)
{
}
@ -15,27 +15,24 @@ void WorldView::draw(sf::RenderWindow *window) const
void WorldView::update(Game *game)
{
// Initialize if necessary
if (view == nullptr)
{
initializeView(game);
}
// Update size
auto windowSize = game->window->getSize();
sf::Vector2f viewSize = sf::Vector2f(windowSize.x, windowSize.y);
view->setSize(viewSize);
setSize(game->window->getSize());
// Update position
auto moveDirection = InputMapper::getInputDirection();
if (moveDirection != InputDirection::NONE)
{
float stepSize = 100.0f * FRAME_TIME.asSeconds();
auto delta = stepSize * Direction::getVector(moveDirection);
this->view->move(delta);
}
moveViewByControls();
// TODO: Only update if necessary
game->window->setView(*this->view);
// Update window if necessary
if (hasViewChanged)
{
game->window->setView(*this->view);
hasViewChanged = false;
}
}
void WorldView::initializeView(Game *game)
@ -44,3 +41,24 @@ void WorldView::initializeView(Game *game)
auto size = game->window->getView().getSize();
view = new sf::View(center, size);
}
void WorldView::setSize(sf::Vector2u windowSize)
{
sf::Vector2f viewSize = sf::Vector2f(windowSize.x, windowSize.y);
view->setSize(viewSize);
hasViewChanged = true;
}
void WorldView::moveViewByControls()
{
auto moveDirection = InputMapper::getInputDirection();
if (moveDirection == InputDirection::NONE)
{
return;
}
float stepSize = 100.0f * FRAME_TIME.asSeconds();
auto delta = stepSize * Direction::getVector(moveDirection);
this->view->move(delta);
hasViewChanged = true;
}

View file

@ -18,8 +18,13 @@ public:
private:
sf::View *view;
bool hasViewChanged;
void initializeView(Game *game);
void setSize(sf::Vector2u windowSize);
void moveViewByControls();
};