I’m writing a plugin for the Godot game engine that uses SDL to expose the internal scripting to a controller’s motion controls.
Since I know precisely nothing about SDL2, I bundled everything short of SDL_Init()
into a single getter method:
godot::Vector3 Motion::get_sensor(int device, SDL_SensorType type) const {
int joystick_count = SDL_NumJoysticks();
// Return blank vectors for invalid indexes.
if(joystick_count == 0 || joystick_count >= device)
return godot::Vector3();
SDL_GameController* controller = SDL_GameControllerOpen(device);
// Return blank vectors if the specified sensor is missing.
if(controller == NULL
|| !SDL_GameControllerHasSensor(controller, type)
|| !SDL_GameControllerSetSensorEnabled(controller, type, true))
return godot::Vector3();
// Pull the sensor data.
float a[3];
SDL_GameControllerGetSensorData(controller, a, type, 3);
SDL_GameControllerClose(controller);
return godot::Vector3(a[0], a[1], a[2]);
}
Aside from running SDL_Init(SDL_INIT_GAMECONTROLLER|SDL_INIT_SENSOR)
in the plugin’s requisite initializer, this is the only thing the plugin does. There are two methods that call get_sensor()
for the accelerometer and gyroscope respectively (which the scripting engine calls), but those are hardly true moving parts.
Would opening and closing the controllers on each frame during gameplay be expensive? Is this considered bad practice? My intention was to make this plugin’s footprint as small as possible, so I made it remember nothing about the hardware or state of the program overall.
It’d be nice if this was all I needed to do, but I can see how it might be too minimalist.