SDL_KEYDOWN和密钥识别无法正常工作 [英] SDL_KEYDOWN and key recognition not working properly

查看:94
本文介绍了SDL_KEYDOWN和密钥识别无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我很难获得一个简单的switch语句以用于SDL输入.这是示例:

In my project I am having trouble getting a simple switch statement to work for SDL input. Here is the example:

SDL_Event event;

SDL_PollEvent(&event);


if (event.type == SDL_KEYDOWN)
{

    switch (event.key.keysym.sym)
    {
    case SDLK_a: m_x -= 30;
            break;
    case SDLK_d: m_x += 30;
            break;
    case SDLK_w: m_y -= 30;
            break;
    case SDLK_s: m_y += 30;
            break;
    }
}

运行此命令时,首先似乎无法识别SDL_KEYDOWN.我的案子也没有.所以我将代码切换为:

When I run this, first off it seems SDL_KEYDOWN isn't being recognized. Nor are my cases. So I switched the code to:

SDL_Event event;

SDL_PollEvent(&event);


if (event.type == 771)
{

    switch (event.key.keysym.sym)
    {
    case SDLK_a: m_x -= 30;
            break;
    case SDLK_d: m_x += 30;
            break;
    case SDLK_w: m_y -= 30;
            break;
    case SDLK_s: m_y += 30;
            break;
    default: m_y += 1;
    }
}

这将导致在按住或按任意键时运行默认大小写,因此我的对象根据m_y + = 1移动.如果删除默认大小写并尝试按w,a,s或d,则什么也没有发生.如果我保持m_y + = 1,但使用SDL_KEYDOWN而不是771,则什么也不会发生. (每当按下一个键时,我都会通过打印event.type来获得771代码).

This causes the default case to run when I hold or press any key, so my object moves according to m_y += 1. If I remove the default case and try pressing w,a,s, or d, nothing happens. If i keep m_y += 1, but use SDL_KEYDOWN instead of 771, nothing happens. (I got the 771 code by printing the event.type whenever a key is being pressed).

推荐答案

您仅调用SDL_PollEvent()一次,因此它给出的是最先发生的事件,可能不是SDL_KEYDOWN.
您必须进行main循环来处理事件:

You call SDL_PollEvent() only once, so it gives the event which occurred first which might not be SDL_KEYDOWN.
You must make a main loop to handle your events:

SDL_Event event;
bool quit=false;    
while(!quit)
{
    while(SDL_PollEvent(&event)
    {
        if(event.type==SDL_KEYDOWN)
        {
             ....
        }
        else if(event.type==SDL_QUIT)
        {
            quit=true;
        }
    }
}

此循环处理您不关心的事件(例如MOUSEMOTION).

This loop takes care of the events which you don't care about(for e.g. MOUSEMOTION).

如果要处理许多不同类型的事件,也可以将switchevent.type一起使用.

And you can also use switch with event.type if you are going to handle many different types of events.

这篇关于SDL_KEYDOWN和密钥识别无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆