我正在创建一个简单的游戏,我正在使用 SDL2 处理来自 Controller 的输入。问题是 SDL 没有给我正确的 Controller 索引,这导致我的游戏崩溃。
/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;
}
当用户第一次添加 Controller 时,这工作得很好,SDL 向我发送 0 作为 SDL_CONTROLLERDEVICEADDED 事件中的索引,也为其他事件发送 0。 问题是,如果用户尝试断开连接并重新连接 Controller ,SDL 会在 SDL_CONTROLLERDEVICEADDED 事件中发送 0 作为索引,而在导致游戏崩溃的其他事件中发送 1。
我也可以简单地检查索引是否可以避免崩溃,但它是无用的,因为所有 Controller 事件都将被忽略。
我们将不胜感激。
谢谢
最佳答案
根据 SDL documentation , SDL_GameControllerOpen 上使用的索引不是将在未来事件中识别 Controller 的索引。因此,您需要改用操纵杆 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;
}
}
关于c++ - SDL 正在发送错误的 Controller 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34831388/