Search code examples
c++sfml

SFML Views vs window confusion


I have this single c++ / SFML code...

#include <SFML/Graphics.hpp>

#define windowWidth  600
#define windowHeight 300

int main()
{
   sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML Views");

   sf::View view(sf::FloatRect(0,0, windowWidth, windowHeight));
   view.zoom(2);
   window.setView(view);


   sf::RectangleShape back (sf::Vector2f(windowWidth, windowHeight));
   back.setFillColor(sf::Color::White);

   sf::RectangleShape rect (sf::Vector2f(200, 100));
   rect.setFillColor(sf::Color::Red);
   rect.setPosition(windowWidth - rect.getSize().x, windowHeight - rect.getSize().y); // position in the lower right corner

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(back);
        window.draw(rect);
        window.display();
    }

    return 0;
}

...which might position the red rectangle in the lower right corner of the window.

However, when I zoom the view in (as in the code), it obviously moves along with the entire window like this image. I have some doubts:

  1. To correct the positioning of the red rectangle and place it in the lower right corner of the global window, I currently have to do some calculations considering the zoom factor, original rectangle size, etc. Is there any easier way to position this rectangle in the lower-right corner of the global window?
  2. How do I prevent some objects from being resized by the zoom of the view?
  3. What do I have to do to have multiple active views in the same window?

Solution

  • Is there any easier way to position this rectangle in the lower-right corner of the global window?

    From SFML 2D camera tutorial: "To draw something using a view, you must draw it after calling the setView function of the target to which you are drawing"

    So the drawing part should be

    window.clear();
    window.setView(view);
    window.draw(back);
    window.setView(window.getDefaultView()); //don't zoom red rect
    window.draw(rect);
    window.display();
    

    What do I have to do to have multiple active views in the same window?

    Just call setView() for each active view and then drawing all the things in that view (again, if needed)

    window.setView(leftHalfView);
    window.draw(a);
    window.draw(b);
    window.draw(c);
    window.setView(rightHalfView);
    window.draw(a);
    window.draw(b);
    window.draw(c);
    window.setView(minimap);
    window.draw(a);
    window.draw(b);
    window.setView(window.getDefaultView());
    window.draw(x);
    window.draw(y);