c++ - 键盘事件未在 sdl 的 cpp 中加载
问题描述
hello
当我点击键时,我试图让它成为我的屏幕打印a
......当我按下2
键时切换图像......但是当我这样做时,没有任何反应,我不知道为什么......它没有给我由于某些奇怪的原因而出现错误...如果您有任何想法,请在下面的评论中告诉我。我已经列出了那里的代码!
#include <SDL.h>
#include <iostream>
int main(int argc, char* argv[])
{
SDL_Window* window = nullptr;
SDL_Surface* WindowSurface = nullptr;
SDL_Surface* image1 = nullptr;
SDL_Surface* image2 = nullptr;
SDL_Surface* currentImage = nullptr;
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("sdl Window",
SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480,
SDL_WINDOW_SHOWN);
WindowSurface = SDL_GetWindowSurface(window);
image1 = SDL_LoadBMP("Red_sheet_full_2.bmp");
image2 = SDL_LoadBMP("Red_sheet_fullA.bmp");
currentImage = image2;
bool isRunning = true;
SDL_Event ev;
while (isRunning)
{
while (SDL_PollEvent(&ev) != 0);
{
if (ev.type == SDL_QUIT)
isRunning = false;
else if (ev.type == SDL_KEYDOWN)
{
switch (ev.key.keysym.sym)
case SDLK_a:
printf("hello");
break;
switch (ev.key.keysym.sym)
case SDLK_2:
currentImage = image1;
break;
}
}
SDL_BlitSurface(currentImage, NULL, WindowSurface, NULL);
SDL_UpdateWindowSurface(window);
}
SDL_FreeSurface(image1);
SDL_FreeSurface(image2);
SDL_DestroyWindow(window);
currentImage = image1 = image2 = nullptr;
window = nullptr;
SDL_Quit();
return 0;
}
解决方案
问题出在switch
声明中。thebreak
在switch
so 之外,如果您收到的第一个事件不是SDLK_a
,它将while
在打印之前跳出循环hello
并退出。
这是正在发生的事情的简化版本:https ://godbolt.org/z/9eEcEYGhj
#include <iostream>
int main(int argc, char* argv[])
{
while (true)
{
char c{'p'};
switch (c)
case 'a':
std::cout << "a\n";
break; // exits without printing anything
switch (c)
case 'b':
std::cout << "b\n";
break;
std::cout << c;
}
}
你有不同的方法来修复它。
一种是以适当的方式编写switch
声明:https ://godbolt.org/z/99MohaTMx
#include <iostream>
int main(int argc, char* argv[])
{
while (true)
{
char c{'a'};
switch (c)
{
case 'a':
std::cout << "a\n"; // forever prints "a\n"
break;
case 'b':
std::cout << "b\n";
break;
default:
break;
}
}
}
另一个,仅用于您当前的实现,将使用 anif-else if
而不是 a switch
。
推荐阅读
- c# - 在 Xamarin.Android 使用的 NuGet 包中包含本机库
- javascript - [Vue 警告]:使用带有参数的 mixin 时无法挂载组件
- android - 将触摸事件从对话框片段传递到正下方的视图(在父活动内)
- google-apps-script - 在 Google 表格上的脚本中从右到左对齐希伯来语文本
- php - 执行数据库连接的 PHP 脚本后未显示成功或失败消息
- python - conda install 是否仍然找不到 jupyter 实验室的模块
- javascript - 你能在没有网络工作者的情况下停止 chrome 休眠选项卡吗
- c - Linux终端中C语言中用户输入的遗忘代码
- ruby-on-rails - 急切地加载 Rails 中关联实体的子集
- hadoop - Hadoop 中 Namenode 的内存