SDL 正在发送错误的控制器索引

SDL is sending a wrong controller index

我正在创建一个简单的游戏,我正在使用 SDL2 处理来自控制器的输入。问题是 SDL 没有给我正确的控制器索引,导致我的游戏崩溃。

/receive the controller index given by SDL
int cIdx = evt.cdevice.which;

switch (evt.type)
{
    case SDL_CONTROLLERAXISMOTION:
    {
        //.........
        break;
    }
    case SDL_CONTROLLERBUTTONUP:
    {

        InputButton sender = InputButton(evt.cbutton.button);

        controllerStates[cIdx]->SetButtonState(sender, false);
        break;
    }
    case SDL_CONTROLLERBUTTONDOWN:
    {
        if (evt.cbutton.button != SDL_CONTROLLER_BUTTON_INVALID)
        {
            InputButton sender = InputButton(evt.cbutton.button);

            controllerStates[cIdx]->SetButtonState(sender, true);
        }
        break;
    }
    case SDL_CONTROLLERDEVICEADDED:
    {
        if (SDL_IsGameController(cIdx))
        {
            SDL_GameController * controller = SDL_GameControllerOpen(cIdx);

            AddController(controller);
        }
        break;
    }
    case SDL_CONTROLLERDEVICEREMOVED:
    {
        RemoveController(controllers[(cIdx)]);
        break;
    }

}

当用户第一次添加控制器时,这工作得很好,SDL 向我发送 0 作为 SDL_CONTROLLERDEVICEADDED 事件中的索引,也为其他事件发送 0。 问题是,如果用户尝试断开连接并重新连接控制器,SDL 在 SDL_CONTROLLERDEVICEADDED 事件中发送 0 作为索引,并为导致游戏崩溃的其他事件发送 1。

我也可以简单地检查索引是否可以避免崩溃,但这将毫无用处,因为所有控制器事件都将被忽略。

任何帮助将不胜感激。

谢谢

根据 SDL documentation,在 SDL_GameControllerOpen 上使用的索引不是将在未来事件中识别控制器的索引。所以你需要改用操纵杆id。

    switch (evt.type)
    {
        case SDL_CONTROLLERAXISMOTION:
        {
            //...
            break;
        }
        case SDL_CONTROLLERBUTTONUP:
        {
            //Get the joystick id from the controller index 
            //....
            break;
        }
        case SDL_CONTROLLERBUTTONDOWN:
        {
            //Get the joystick id from the controller index 
            //....
            break;
        }
        case SDL_CONTROLLERDEVICEADDED:
        {
            if (SDL_IsGameController(cIdx))
            {
                SDL_GameController * controller = SDL_GameControllerOpen(cIdx);
                SDL_Joystick* j      = SDL_GameControllerGetJoystick(controller);
                SDL_JoystickID joyId = SDL_JoystickInstanceID(j);

                //Save the joystick id to used in the future events
                AddController(controller);
            }
            break;
        }
        case SDL_CONTROLLERDEVICEREMOVED:
        {
             //Get the joystick id from the controller index 

            break;
        }
   }