SDL 输入有时只能工作
SDL inputs only working sometimes
我在 SDL 中尝试键盘输入,但遇到了一个奇怪的问题。每当我输入时,它有时只会输出适当的响应(单击 X 有时会关闭程序,仅按 1 有时会输出 "you pressed 1"。这是我的主要代码:
#include <iostream>
#include <SDL.h>
#include "Screen.h"
#include "Input.h"
using namespace std;
int main(int argc, char *argv[]) {
Screen screen;
Input input;
if (screen.init() == false) {
cout << "Failure initializing SDL" << endl;
}
while (true) {
if (input.check_event() == "1") {
cout << "You pressed 1" << endl;
} else if (input.check_event() == "quit") {
break;
}
}
SDL_Quit();
return 0;
这是我的输入 class:
#include <iostream>
#include <SDL.h>
#include "Input.h"
using namespace std;
string Input::check_event() {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return "quit";
}
else if(event.type == SDL_KEYDOWN){
switch(event.key.keysym.sym){
case SDLK_1:
return "1";
}
}
}
return "null";
}
如有任何帮助,我们将不胜感激!
来自 SDL_PollEvent()
的文档:
If event is not NULL, the next event is removed from the queue and
stored in the SDL_Event structure pointed to by event.
正在分析您的代码:
if (input.check_event() == "1") {
这 从队列中删除 事件,无论它是什么。
} else if (input.check_event() == "quit") {
假设第一次调用 check_event()
的 return 值为 "quit",则此调用不会再次 return "quit",因为这信息现在丢失了。
要解决此问题,请在每次循环迭代中仅调用一次 check_event()
,并将结果存储在临时变量中。然后在条件中仅使用该变量:
while (true) {
string event = input.check_event();
if (event == "1") {
cout << "You pressed 1" << endl;
} else if (event == "quit") {
break;
}
}
我在 SDL 中尝试键盘输入,但遇到了一个奇怪的问题。每当我输入时,它有时只会输出适当的响应(单击 X 有时会关闭程序,仅按 1 有时会输出 "you pressed 1"。这是我的主要代码:
#include <iostream>
#include <SDL.h>
#include "Screen.h"
#include "Input.h"
using namespace std;
int main(int argc, char *argv[]) {
Screen screen;
Input input;
if (screen.init() == false) {
cout << "Failure initializing SDL" << endl;
}
while (true) {
if (input.check_event() == "1") {
cout << "You pressed 1" << endl;
} else if (input.check_event() == "quit") {
break;
}
}
SDL_Quit();
return 0;
这是我的输入 class:
#include <iostream>
#include <SDL.h>
#include "Input.h"
using namespace std;
string Input::check_event() {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
return "quit";
}
else if(event.type == SDL_KEYDOWN){
switch(event.key.keysym.sym){
case SDLK_1:
return "1";
}
}
}
return "null";
}
如有任何帮助,我们将不胜感激!
来自 SDL_PollEvent()
的文档:
If event is not NULL, the next event is removed from the queue and stored in the SDL_Event structure pointed to by event.
正在分析您的代码:
if (input.check_event() == "1") {
这 从队列中删除 事件,无论它是什么。
} else if (input.check_event() == "quit") {
假设第一次调用 check_event()
的 return 值为 "quit",则此调用不会再次 return "quit",因为这信息现在丢失了。
要解决此问题,请在每次循环迭代中仅调用一次 check_event()
,并将结果存储在临时变量中。然后在条件中仅使用该变量:
while (true) {
string event = input.check_event();
if (event == "1") {
cout << "You pressed 1" << endl;
} else if (event == "quit") {
break;
}
}