【问题标题】:GLFW input handling not working as intendedGLFW 输入处理未按预期工作
【发布时间】:2016-07-06 11:34:11
【问题描述】:

所以这可能是关于 GLFW 的新手问题,但我似乎遇到了一个有趣的问题。所以我正在使用 GLFW 开发一个简单的输入处理类,特别是利用静态方法来允许只需要包含头文件来使用这些方法。所以这是我迄今为止的代码......

InputHandler.cpp

#include "InputHandler.h"

GLFWwindow *Input::m_Window;
bool Input::isDown;
std::vector<int> Input::keyCache;

void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    for (int _key = 0; _key < Input::keyCache.size(); _key++)
    {
        if (key == Input::keyCache[_key] && action == GLFW_PRESS || key == Input::keyCache[_key] && action == GLFW_REPEAT)
            Input::isDown = true;
        else
            Input::isDown = false;
    }
}

void Input::processInput(GLFWwindow* window)
{
    m_Window = window;
}

bool Input::isKeyDown(int key)
{
    keyCache.push_back(key);
    glfwSetKeyCallback(m_Window, key_callback);
    return isDown;
}

InputHandler.h

#pragma once

#include <GLFW\glfw3.h>
#include <vector>

class Input
{
public:
    static bool isDown;
    static std::vector<int> keyCache;
private:
    static GLFWwindow *m_Window;

public:
    static void processInput(GLFWwindow* window);
    static bool isKeyDown(int key);
    static bool isKeyUp(int key);
    static int getMouseX();
    static int getMouseY();
};

但是,每当我调用 isKeyDown 方法时,该方法将根据键是否按下而返回 true 或 false,多次,程序似乎只响应提到的最后一个键。例如,如果我使用代码...

if (Input::isKeyDown(GLFW_KEY_W) || Input::isKeyDown(GLFW_KEY_Q))
        std::cout << "Key is down" << std::endl;

只有 Q 键会触发语句,W 什么也不做。我已经多次浏览 GLFW 的网站,输入指南是我学习接收输入所需的必要内容的地方,而且似乎没有其他人遇到过这个问题,因为我已经搜索过任何东西。如果有人可以通过解释可能的问题或在我自己找到答案方面指出正确的方向来提供帮助,我将不胜感激!

【问题讨论】:

  • 当 W 和 Q 都在缓存中并且只有 W 被按下时,你认为 key_callback 会做什么?答案:将 isDown 设置为 true,然后将 isDown 设置为 false,然后返回。所以在这种情况下 isDown 是假的。
  • 是的,这对我来说很有意义。或许我之前应该明白这一点,但我会一直告诉自己,已经很晚了,我很累。感谢您抽出宝贵时间回复@immibis

标签: c++ input glfw


【解决方案1】:

好的,我发现了我的问题。我太复杂了。所以,我的问题是键回调只能处理一个键,这是完全没有必要的。因此,我的修复涉及删除键回调、keyCache 和 isDown 变量,并简单地将 isKeyDown 更改为...

bool Input::isKeyDown(int key)
{
    if (glfwGetKey(m_Window, key))
        return true;

    return false;
}

我很抱歉我表现出自己的无能可笑。好吧,现在我知道关键回调是如何工作的了! xD

【讨论】:

    猜你喜欢
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多