gpt4 book ai didi

c - SDL_GetKeyboardState 不起作用

转载 作者:行者123 更新时间:2023-11-30 17:34:28 27 4
gpt4 key购买 nike

我正在尝试使用 SDL 2 为游戏制作一个 Controller (不想询问 gamedev,因为这不是直接的游戏问题)我使用 SDL_GetKeyboardEvent 来查看导航箭头是否被按下,但显然没有不起作用,如果按下其中一个键,它应该打印值 1 或 -1,但事实并非如此,即使我按住该键几秒钟,它也只会打印 0,就像它没有检测到一样正在按下该键。我在互联网上进行了搜索,他们就是这样做的,但它对我不起作用。

#define SDL_MAIN_HANDLED
#include <stdio.h>
#include "SDL.h"

/* I'll add some code later
so something that isn't used
might be initialized
*/
int main (void)
{
int a = 1;
int x;
int z;
SDL_Event quit;
const Uint8 *keys = SDL_GetKeyboardState(NULL);

SDL_Init(SDL_INIT_VIDEO);

while(a)
{
SDL_PollEvent(&quit);
if(quit.type == SDL_QUIT)
a = 0;

if(keys[SDL_SCANCODE_UP])
z = 1;
else if(keys[SDL_SCANCODE_DOWN])
z = -1;
else
z = 0;
if(keys[SDL_SCANCODE_LEFT])
x = -1;
else if(keys[SDL_SCANCODE_RIGHT])
x = 1;
else
x = 0;
printf("%d, %d\n", x, z);
//This is supposed to print
//x, z values so if up arrow is pressed it will print 0, 1 and if
//down arrow is pressed it will print 0, -1: the same with horizontal ones.
//1 or -1, 1 or -1
}

SDL_Quit();
return 0;
}

最佳答案

阅读文档:wiki

注意:此函数为您提供处理所有事件后的当前状态,因此如果在处理事件之前按下并释放了某个键或按钮,则按下的状态将永远不会显示在 SDL_GetKeyboardState( ) 调用

这是什么意思?

您需要处理所有事件。如何?循环PollEvent,循环结束后(或者如果您想在循环中检查,请在最后检查),SDL_GetKeyboardState 可用。

因此,通过循环检查键盘状态。不要忘记在检查 key 之前始终执行循环

例如

while (game)
{
/*! updates the array of keystates */
while ((SDL_PollEvent(&e)) != 0)
{
/*! request quit */
if (e.type == SDL_QUIT)
{
game = false;
}
}

if (keys[SDL_SCANCODE_RIGHT])
std::cout << "Right key";
}

关于c - SDL_GetKeyboardState 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328847/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com