所以我得到了这个应该模仿控制台的程序(在 this user 的一点编码帮助下):
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
sf::Color fontColor;
sf::Font mainFont;
sf::Clock myClock;
bool showCursor = true;
void LoadFont() {
mainFont.loadFromFile("dos.ttf");
fontColor.r = 0;
fontColor.g = 203;
fontColor.b = 0;
}
int main() {
sf::RenderWindow wnd(sf::VideoMode(1366, 768), "SFML Console");
wnd.setSize(sf::Vector2u(1366, 768));
LoadFont();
sf::Text myTxt;
myTxt.setColor(fontColor);
myTxt.setString("System Module:");
myTxt.setFont(mainFont);
myTxt.setCharacterSize(18);
myTxt.setStyle(sf::Text::Regular);
myTxt.setPosition(0, 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();
if (myClock.getElapsedTime() >= sf::milliseconds(500)) {
myClock.restart();
showCursor = !showCursor;
if(showCursor == true) {
myTxt.setString("System Module:_");
} else {
myTxt.setString("System Module:");
}
}
wnd.draw(myTxt);
wnd.display();
}
}
我需要能够让用户在键盘上键入一个键,然后在屏幕上呈现该键。我正在考虑使用 std::vector
的 sf::Keyboard::Key
,并使用 while 循环来检查 key 是什么(循环通过 std::vector<sf::Keyboard::Key>
)而不使用一大堆 if
语句,但我还不知道如何处理,所以我想知道是否有更简单的方法来实现我的主要目标。建议?评论?
谢谢你的时间, ~迈克
最佳答案
SFML 对此有一个很好的特性,sf::Event::TextEntered
( tutorial )。这通常是您想要的,它可以避免您做疯狂的事情来解释用户输入的文本。
通过将每个字符添加到 sf::String
(而不是 std::string
,它可能更好地处理 sfml 的 unicode 类型来存储您输入的文本 ~ 不确定,但是需要一点检查)这是 sf::Text::setString
的完美类型!
不要犹豫,看看 docs ,它在每个类的页面中都有进一步的文档。
例子:
sf::String userInput;
// ...
while( wnd.pollEvent(event))
{
if(event.type == sf::Event::TextEntered)
{
/* Choose one of the 2 following, and note that the insert method
may be more efficient, as it avoids creating a new string by
concatenating and then copying into userInput.
*/
// userInput += event.text.unicode;
userInput.insert(userInput.getSize(), event.text.unicode);
}
else if(event.type == sf::Event::KeyPressed)
{
if(event.key.code == sf::Keyboard::BackSpace) // delete the last character
{
userInput.erase(userInput.getSize() - 1);
}
}
}
关于c++ - SFML - 按下键时呈现字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17256015/