【发布时间】: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