Skip to content

Commit

Permalink
sdl: use controller accelerometer for tilt if available
Browse files Browse the repository at this point in the history
  • Loading branch information
Daft-Freak committed Jan 24, 2025
1 parent b365c5a commit 4868a09
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
14 changes: 13 additions & 1 deletion 32blit-sdl/Input.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ std::map<int, int> Input::keys = {
{SDLK_1, blit::Button::HOME},
{SDLK_2, blit::Button::MENU},
{SDLK_3, blit::Button::JOYSTICK},

{SDLK_ESCAPE, blit::Button::MENU},
};

Expand Down Expand Up @@ -151,6 +151,13 @@ bool Input::handle_controller_motion(int axis, int value) {
return false;
}

bool Input::handle_controller_accel(float data[3]) {
target->set_tilt(0, -data[0]);
target->set_tilt(1, -data[2]);
target->set_tilt(2, data[1]);
return true;
}

void Input::handle_controller_added(Sint32 joystick_index) {

SDL_GameController* gc = SDL_GameControllerOpen(joystick_index);
Expand Down Expand Up @@ -201,6 +208,11 @@ void Input::_add_controller(SDL_GameController* gc) {
// welcome rumble to test if it can rumble
auto can_rumble = SDL_GameControllerRumble(gc, 0xFFFF, 0xFFFF, 200);

#if SDL_VERSION_ATLEAST(2, 0, 14)
// enable accelerometer if present
SDL_GameControllerSetSensorEnabled(gc, SDL_SENSOR_ACCEL, SDL_TRUE);
#endif

GameController gcs = {gc, can_rumble == 0};
game_controllers.push_back(gcs);
}
Expand Down
1 change: 1 addition & 0 deletions 32blit-sdl/Input.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Input {
bool handle_keyboard(int key, bool state);
bool handle_controller_button(int button, bool state);
bool handle_controller_motion(int axis, int value);
bool handle_controller_accel(float data[3]);

// controller specific functions
void handle_controller_added(Sint32 joystick_index);
Expand Down
7 changes: 7 additions & 0 deletions 32blit-sdl/Main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ void handle_event(SDL_Event &event) {
blit_input->handle_controller_removed(event.cdevice.which);
break;

#if SDL_VERSION_ATLEAST(2, 0, 14)
case SDL_CONTROLLERSENSORUPDATE:
if(event.csensor.sensor == SDL_SENSOR_ACCEL)
blit_input->handle_controller_accel(event.csensor.data);
break;
#endif

case SDL_RENDER_TARGETS_RESET:
std::cout << "Targets reset" << std::endl;
break;
Expand Down
1 change: 1 addition & 0 deletions 32blit-sdl/System.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ bool System::loop() {
blit::tilt.x = shadow_tilt[0];
blit::tilt.y = shadow_tilt[1];
blit::tilt.z = shadow_tilt[2];
blit::tilt.normalize();
accel_data.data = blit::tilt;

blit::joystick.x = shadow_joystick[0];
Expand Down

0 comments on commit 4868a09

Please sign in to comment.