Search code examples
c++sfml

Changing the world origin in C++ SFML


I've recently gotten into SFML and as an exercise to get more comfortable (and have fun), I started translating some Coding Challenges done by Daniel Shiffman on his Youtube channel, The Coding Train. Upon attempting to translate a star field effect in SFML, I started searching for the right function in SFML that would change the world origin from the top-left of the screen to the center. The closest thing I found to this was the setOrigin function, but that only works for sprites and not the whole window/screen. If you didn't understand my description of this function, it would be the equivalent of the translate(x, y) function in Processing. Any help would be appreciated.


Solution

  • You need to use sf::View https://www.sfml-dev.org/tutorials/2.5/graphics-view.php

    Here is a small implementation example:

    #include <SFML/Graphics.hpp>
    
    int main()
    {
        sf::RenderWindow window(sf::VideoMode(300, 300), "");
        sf::Vector2u size = window.getSize();
        sf::View view(sf::Vector2f(0, 0), sf::Vector2f(size.x, size.y));
        window.setView(view);
    
        sf::CircleShape cir(10);
        cir.setOrigin(10, 10);
    
        while(window.isOpen())
        {
            sf::Event event;
            while (window.pollEvent(event))
                if (event.type == sf::Event::Closed)
                    window.close();
        
            window.clear();
            window.draw(cir);
            window.display();
        }
        return 0;
    }