【问题标题】:SFML - Creating a cursor and printing input?SFML - 创建光标和打印输入?
【发布时间】:2013-06-19 06:43:50
【问题描述】:

所以我已经下载了 SFML,到目前为止我很喜欢它。我遇到了障碍,并试图弄清楚如何在下面的代码中实现闪烁光标。我还需要弄清楚如何在窗口上打印单个字符(当用户按下键盘上的键时)。这是我下载 SFML 2.0 后一直使用的一些代码:

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <iostream>

int main() {
    sf::RenderWindow wnd(sf::VideoMode(650, 300), "SFML Console");
    sf::Vector2u myVector(650, 300);
    wnd.setSize(myVector);

    sf::Font myFont;
    myFont.loadFromFile("theFont.ttf");

    sf::Color myClr;
    myClr.r = 0;
    myClr.g = 203;
    myClr.b = 0;

    sf::String myStr = "Hello world!";
    std::char myCursor = '_';

    sf::Text myTxt;
    myTxt.setColor(myClr);
    myTxt.setString(myStr);
    myTxt.setFont(myFont);
    myTxt.setCharacterSize(12);
    myTxt.setStyle(sf::Text::Regular);
    myTxt.setPosition(0, 0);

    std::int myCounter = 0;

    while(wnd.isOpen()) {
        sf::Event myEvent;

        while (wnd.pollEvent(myEvent)) {
            if (myEvent.type == sf::Event::Closed) {
                wnd.close();
            }

            if (myEvent.type == sf::Event::KeyPressed) {
                if (myEvent.key.code == sf::Keyboard::Escape) {
                    wnd.close();
                }
            }

            wnd.clear();
            wnd.draw(myTxt);

            myCounter++;
            std::if (myCounter >= 1000) {
                myCounter = 0;
            }

            std::if (myCounter < 1000) {
                myTxt.setString("Hello world!_");
            }

            wnd.display();
        }
    }
}

【问题讨论】:

    标签: c++ windows gcc sfml tdm-mingw


    【解决方案1】:

    使用sf::Clock (doc)。

    在主循环之前声明您的时钟以及其他变量,这也会自动启动时钟。在您的循环中,检查经过的时间并重置时钟,如果它超过了您想要的。示例:

    sf::Clock myClock; // starts the clock
    bool showCursor = false;
    
    // ...
    
    wnd.draw(myTxt);
    
    if(clock.getElapsedTime() >= sf::milliseconds(500))
    {
        clock.restart();
        showCursor = !showCursor;
        if(showCursor)
            myTxt.setString("Hello World!_");
        else
            myTxt.setString("Hello World!");
    }
    
    // ...
    

    这应该会让你的光标闪烁 0.5 秒。

    顺便问一下,你为什么使用std::if() 而不是语言中包含的普通if

    【讨论】:

    • 谢谢。我想我现在明白了。哦,std::if 是一个简单的错误,我已将其替换为正常的 if。
    • 嗯,我刚刚用您的示例测试了我的代码,显然我需要让鼠标不断地在 SFML 屏幕上移动以使光标闪烁。有没有办法让光标闪烁,而我不必以恒定的方式移动鼠标来让光标闪烁?来源:pastebin.com/VjBNgpPC
    • @Mike 关闭您的while (wnd.pollEvent(myEvent)) {} 放错了位置。它应该在您测试完事件后立即关闭(即,pastebin 中的第 45 行)。现在,您的代码仅在您的窗口有事件时运行,这就是您需要移动鼠标的原因。另一件事,您应该将if(showCursor)/else 放在测试经过时间的if 内:您只需要在时间超过500ms 时将文本更改为绘制一次,而不是在每一帧。
    • 啊!感谢那。所以这个程序应该模仿一个控制台窗口。对于我的下一个问题,应该开始一个新问题,还是在这个问题上提问?
    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 2017-06-02
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多