SDL2 操纵杆事件未触发

SDL2 joystick event not triggering

所以我得到了这个代码:

void Engine::Run() {
    // initialize all components
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK))
        throw Exception("couldn't initialize SDL\n" + string(SDL_GetError()), 1);

    // other code

    run = true;
    SDL_Event event;

    while (run) {
        // other code

        uint32 timeout = SDL_GetTicks() + 50;
        while (SDL_PollEvent(&event) && timeout - SDL_GetTicks() > 0)
            HandleEvent(event);
    }
}

void Engine::HandleEvent(const SDL_Event& event) {
    switch (event.type) {
    case SDL_KEYDOWN:
        inputSys->KeyDownEvent(event.key);
        break;
    case SDL_KEYUP:
        inputSys->KeyUpEvent(event.key);
        break;
    case SDL_JOYBUTTONDOWN:
        cout << "button" << endl;
        break;
    case SDL_JOYHATMOTION:
        cout << "hat" << endl;
        break;
    case SDL_JOYAXISMOTION:
        cout << "axis" << endl;
        break;
    case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED:
        inputSys->UpdateControllers();
        break;
    // other code
    }
}

问题是唯一没有被调用的事件是操纵杆按钮、帽子和轴事件。其他两个操纵杆相关事件工作得很好。
我在不同的项目中使用完全相同的代码,其中所有操纵杆事件都可以毫无问题地调用,但是自从我将代码移至我的新项目后,它们就不再被调用了。
SDL 确实识别插入的控制器,我可以使用像 SDL_JoystickGetAxis 这样的函数,但出于某种原因,这三个事件似乎不起作用。知道这是为什么吗?

您必须调用 SDL_JoystickOpen 才能获取这些事件。这是他们的例子:

SDL_Joystick *joy;

// Initialize the joystick subsystem
SDL_InitSubSystem(SDL_INIT_JOYSTICK);

// Check for joystick
if (SDL_NumJoysticks() > 0) {
    // Open joystick
    joy = SDL_JoystickOpen(0);

    if (joy) {
        printf("Opened Joystick 0\n");
        printf("Name: %s\n", SDL_JoystickNameForIndex(0));
        printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joy));
        printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joy));
        printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joy));
    } else {
        printf("Couldn't open Joystick 0\n");
    }

    // Close if opened
    if (SDL_JoystickGetAttached(joy)) {
        SDL_JoystickClose(joy);
    }
}