我想要一个数组来表示用户刚刚按下的所有键(不是按住,只是按下,就像你在打字一样)。我认为最好的方法是使用 3 个数组 - currentKeyboard(cK)、previousKeyboard(pK) 以及获取当前按下的键的函数 returnKeyboard(rK)。
假设 cK 和 pK 如下所示:
pK = [1 1 0 1 0 1]
cK = [0 1 1 0 1 0]
两者的按位或应该返回
rK = cK | rK //[1 1 1 1 1 1]
并且通过对 rK 和 pK 使用按位异或,它应该给我当前按下的键,而之前没有按下。
[1 1 0 1 0 1]
XOR [1 1 1 1 1 1]
------------------
[0 0 1 0 1 0]
但是,当我运行我的代码时,我似乎总是得到一个 0 数组。 (我假设我的按位运算没有出错;如果有,请告诉我!)
这是我获取按键的代码:
Uint8* KeyboardController::getPressedKeys()
{
Uint8* r_Keyboard= new Uint8[283];
//Loop through every SDL_SCANCODE(starting at 4) and set them to 0 in r_Keyboard
for (int i = 0; i < 283; i++) {
r_Keyboard[i] = 0;
}
//If there is a previous keyboard to compare to
if (m_preKeyboard) {
//Now, compare m_curKeyboard to m_preKeyboard and set 1 in r_Keyboard to any differences (OR pK and cK, then XOR pK with the resultant of OR)
for (int i = 4; i < 283; i++) {
r_Keyboard[i] = m_preKeyboard[i] | m_curKeyboard[i];
r_Keyboard[i] = m_preKeyboard[i] ^ r_Keyboard[i];
}
}
//Testing - am I just getting back a 0 array?
for (int i = 0; i < 283; i++) {
if (r_Keyboard[i]) {
printf("%d\n", i);
}
}
return r_Keyboard;
}
还有我设置 m_curKeyboard 和 m_preKeyboard 的函数:
void KeyboardController::Update()
{
if (m_curKeyboard) {
m_preKeyboard = m_curKeyboard;
}
m_curKeyboard = SDL_GetKeyboardState(NULL);
}
这是主循环代码:
bool isOn = true;
while (isOn)
{
//Pump events(Needed for SDL_GetKeyboardState to work)
SDL_PumpEvents();
keyboard->Update();
//Get window surface
screenSurface = SDL_GetWindowSurface(window);
//Fill the surface white
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
//Update the surface
SDL_UpdateWindowSurface(window);
Uint8 *keysPressed = keyboard->getPressedKeys();
if (keysPressed[SDL_SCANCODE_A]==1) {
printf("A key pressed!\n");
}
if (keysPressed[SDL_SCANCODE_S]==1) {
printf("S key was pressed!\n");
}
if (keysPressed[SDL_SCANCODE_ESCAPE]==1){
isOn = false;
//delete keysPressed;
}
}
现在,如果我在 getPressedKeys() 函数中注释掉 OR 或 XOR 行,我将从程序返回输出。然而,这是徒劳的,因为它会看到一个键被按住而不是被按下时向输出发送垃圾邮件。
最佳答案
您可以使用标准模板库轻松完成此操作。这是一个小例子。另请注意,您需要修复返回对临时引用的引用(请参阅我对该问题的评论)。移动到 std::vector
(如本例所示)将使您的生活更轻松:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
// previous keyboard presses
std::vector<int> prev_kb{0, 0, 0, 1, 1, 0, 0, 0, 1, 1};
// current keyboard presses
std::vector<int> next_kb{0, 1, 1, 1, 1, 1, 0, 0, 1, 0};
// combined keyboard - sized to the size of next
std::vector<int> combined(next_kb.size());
// apply the logical_or<int> algorithm to each keyboard press
std::transform(
prev_kb.begin(),
prev_kb.end(),
next_kb.begin(),
combined.begin(),
logical_or<int>());
// print to verify it worked
std::for_each(
combined.begin(),
combined.end(),
[] (int c)
{
cout << c << ' ';
});
return 0;
}
关于c++ - 返回 0 数组的数组按位或异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21023752/