【问题标题】:SFML, how to change property of a rectangle when a certain condition is metSFML,满足特定条件时如何更改矩形的属性
【发布时间】:2020-07-16 17:25:35
【问题描述】:

所以我刚开始学习 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】:

    你可以使用线程:

    #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();
        }
    }
    

    【讨论】:

    • 非常感谢,我会试试这个
    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多