0

所以我已经下载了 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();
        }
    }
}
4

1 回答 1

2

Use sf::Clock (doc).

Declare your clock along with your other variables before your main loop, this also starts the clock automatically. In your loop, check for the time elapsed and reset the clock if it exceeds what you want. Example :

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!");
}

// ...

This should give you a cursor blinking by 0.5 second.

By the way, why are you using std::if() instead of a plain if that is included in the language ?

于 2013-06-22T11:40:56.030 回答