#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <algorithm>
int main()
{
const sf::Vector2f windowSize(1280, 720);
sf::RenderWindow window(sf::VideoMode(static_cast<unsigned int>(windowSize.x),
static_cast<unsigned int>(windowSize.y)), "SFML");
sf::RectangleShape quad;
quad.setFillColor(sf::Color::White);
quad.setSize(sf::Vector2f(100, 100));
quad.setPosition(100, 100);
const sf::Vector2f cameraSize(640, 480);
sf::View camera;
camera.setSize(cameraSize);
sf::RectangleShape cameraBackground;
cameraBackground.setFillColor(sf::Color(50, 50, 50, 255));
cameraBackground.setSize(cameraSize);
sf::Clock clock;
sf::Vector2f coord;
const int speed = 100;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
sf::Time elapsed = clock.restart();
const float speedMultiplier{ sf::Keyboard::isKeyPressed(sf::Keyboard::LShift) ? 5.f : (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl) ? 0.2f : 1.f) }; // SHIFT = 5x faster, CTRL = 5x slower
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
coord.y -= speed * elapsed.asSeconds() * speedMultiplier;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
coord.y += speed * elapsed.asSeconds() * speedMultiplier;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
coord.x -= speed * elapsed.asSeconds() * speedMultiplier;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
coord.x += speed * elapsed.asSeconds() * speedMultiplier;
const sf::Vector2f overspill{ std::max(-coord.x, 0.f), std::max(-coord.y, 0.f) };
const sf::Vector2f adjustedSize{ cameraSize - overspill };
camera.setCenter(coord + sf::Vector2f(cameraSize.x / 2, cameraSize.y / 2) + (overspill / 2.f));
camera.setSize(adjustedSize);
camera.setViewport(sf::FloatRect(std::max(0.f, coord.x / windowSize.x),
std::max(0.f, coord.y / windowSize.y),
std::max(0.f, adjustedSize.x / windowSize.x), // these are 'clipped' to zero to avoid negative sizes,
std::max(0.f, adjustedSize.y / windowSize.y))); // which cause OpenGL errors
cameraBackground.setPosition(coord);
window.clear();
window.setView(camera);
window.draw(cameraBackground);
window.draw(quad);
window.display();
}
return 0;
}
Note that this only takes into account the top and left borders. If your viewports will pass the right and bottom borders of the window, you will need to expand this idea.