SFML,在满足特定条件时如何更改矩形的属性

问题描述 投票:0回答:1

所以我刚刚开始学习SFML。因此,我想输入x。当x = 1时,我创建的矩形的颜色发生了变化。这是我的代码:

#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
int main()
{
     int x;

     sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close | 
     sf::Style::Titlebar);
     sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);

     while (MW.isOpen()) {
         sf::Event evnt;
         while (MW.pollEvent(evnt)) {
             switch (evnt.type) {
             case sf::Event::Closed:
             MW.close(); break;
             } 
         }
        cin >> x;
        if (x == 1) {
            bg.setFillColor(sf::Color::Blue);
          }

        MW.clear();
        MW.draw(bg);          
        MW.display();
     }
     return 0;
}

现在我面临的问题是窗口无法正确加载。当我将“ cin”移出循环时,我似乎根本无法接受任何输入。

c++ visual-studio visual-c++ graphics sfml
1个回答
0
投票

您可以使用线程:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <mutex>
#include <thread>

int main() {
    std::mutex xmutex;
    int x = 0;
    std::thread thr([&]() {
        std::lock_guard<std::mutex> lock(xmutex);
        int x;
        std::cin >> x;
    });
    thr.detach();

    sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close | sf::Style::Titlebar);
    sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);

    while (MW.isOpen()) {
        sf::Event evnt;
        while (MW.pollEvent(evnt)) {
            switch (evnt.type) {
            case sf::Event::Closed:
                MW.close(); break;
            }
        }

        {
            std::lock_guard<std::mutex> lock(xmutex);
            if (x == 1) {
                bg.setFillColor(sf::Color::Blue);
            }
        }

        MW.clear();
        MW.draw(bg);
        MW.display();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.