【问题标题】:SDL is sending a wrong controller indexSDL 发送错误的控制器索引
【发布时间】:2016-01-17 04:32:10
【问题描述】:

我正在创建一个简单的游戏,并使用 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 在 SDL_CONTROLLERDEVICEADDED 事件中向我发送 0 作为索引,对于其他事件也发送 0。 问题是,如果用户尝试断开并重新连接控制器,SDL 发送 0 作为 SDL_CONTROLLERDEVICEADDED 事件中的索引,发送 1 作为导致游戏崩溃的其他事件。

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

我们将不胜感激。

谢谢

【问题讨论】:

    标签: c++ c sdl


    【解决方案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;
            }
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多