【问题标题】:Is there an easier way have keyboard input return a char (SFML)?有没有更简单的方法让键盘输入返回一个字符(SFML)?
【发布时间】:2020-04-11 00:51:15
【问题描述】:

我想将键盘输入用作函数的参数。我正在尝试获取返回字符的键盘输入:按下的键。

有没有比我现在做的更好的方法?

char getKey() {
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        return 'A';
    } 
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
    {
        return 'A';
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::B))
    {
        return 'B';
    }
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::C))
    {
        return 'C';
    }

    //...

    return '\0';
}

我知道你可以使用 TextEntered,但我不想使用其他 ASCII 键(å、∫、ç、...)

有没有更简单的方法来做到这一点而无需逐个字母?

【问题讨论】:

  • 如果当前按下了多个键,你的函数会返回什么?
  • 也许我应该做一个字符数组?

标签: c++ sfml


【解决方案1】:

您可以只处理代码中的事件

while (window.pollEvent(event)) 
{
    if (event.type == sf::Event::Closed)
    {
        window.close();
        break;
    } 
    else if(event.type == sf::Event::KeyPressed)
    {
        const sf::Keyboard::Key keycode = event.key.code;
        if (keycode == sf::Keyboard::A) 
            std::cout << "A is pressed";
    }
}

【讨论】:

  • @UmarFarooq 是的。
  • 是的! SFML 是跨平台的
【解决方案2】:

字母的枚举字段的排列方式与 ASCII 相同。通过使用此属性,您可以通过添加 abd 来获得一个字符:

#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>

int main() {
    sf::RenderWindow window(sf::VideoMode(1200, 650), "");
    std::string enteredChars;
    enteredChars.reserve(1000);

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed || event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
               window.close();
            } else if (event.type == sf::Event::KeyPressed) {
                const sf::Keyboard::Key keycode = event.key.code;
                if (keycode >= sf::Keyboard::A && keycode <= sf::Keyboard::Z) {
                    char chr = static_cast<char>(keycode - sf::Keyboard::A + 'a');
                    enteredChars.push_back(chr);
                }
            }
        }

        window.clear();
        window.display();
    }

    std::cout << enteredChars << "\n";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2012-06-29
    相关资源
    最近更新 更多