SFML community forums

Help => Graphics => Topic started by: Jan666 on September 15, 2022, 08:48:47 pm

Title: Manage different screens with touch button
Post by: Jan666 on September 15, 2022, 08:48:47 pm
Hello, i have a question i follow the Tutorial "manage for different Screens" on github. Now i wanna i build in a RectangleShape (btn1), who will used for a touch button to cgange on another screen, how i can handld this, here is my code:
class screen_1: public cscreen {
       
        public:        
         screen_1(void);        
        virtual int Run(sf::RenderWindow &App);
        void btn(sf::RenderWindow &App);
       
        private:
        sf::RectangleShape btn1;
        sf::FloatRect btn1Rect;
};

screen_1::screen_1(void){
       
        btn1.setSize(sf::Vector2f(500, 100));
        btn1.setPosition(sf::Vector2f(400, 500));
        btn1.setFillColor(sf::Color::Red);
       
}

void screen_1::btn(sf::RenderWindow &App){
       
        sf::Vector2i pixelPos = sf::Touch::getPosition(0, App);
                sf::Vector2f worldPos = App.mapPixelToCoords(pixelPos);
               
                btn1Rect = btn1.getGlobalBounds();
       
        if(btn1Rect.contains(worldPos)){
               
                screen_2::Run(); //dont work :(
               
}

int screen_1::Run(sf::RenderWindow &App){
       
        sf::Event event;        
        bool Running = true;
       
        while (Running) {              
       
        while (App.pollEvent(event))
        {                              
        if (event.type == sf::Event::Closed)                    {                      
                        return (-1);                   
                        }
                       
                               
                               
                               
                        }
        }
        App.clear(sf::Color(25, 200, 30));
        App.draw(btn1);
        App.display();
       
        }
        return (-1);
}



 

Title: Re: Manage different screens with touch button
Post by: eXpl0it3r on September 20, 2022, 08:23:58 pm
Looking at the mentioned tutorial (https://github.com/SFML/SFML/wiki/Tutorial%3A-Manage-different-Screens) you can change screens by return a specific value.

screen = Screens[screen]->Run(App);

So if you have screen1 at index 0 and screen2 at index 1 and you want to switch from screen1 to screen2, you have the Run function from screen1 return a 1.

While this works, it's a lose connection and can easily lead to out of bound access and hard to follow code flows. I once wrote a C++ version from an older tutorial on state/screen managing, which is a bit overkill at times, but should be a bit more robust, in case you want to see some alternatives: https://github.com/eXpl0it3r/SmallGameEngine