Skip to content

Commit

Permalink
Improve deadzone algorithm and use it for SDL_GameController, fix #111
Browse files Browse the repository at this point in the history
  • Loading branch information
jhasse committed Jan 27, 2025
1 parent 008f3bd commit 9aee239
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
18 changes: 16 additions & 2 deletions src/sdl/controller/SdlController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,26 @@ float SdlController::stateImpl(controller::Button button) const {
otherState *= std::sqrt(1 - 0.5 * state * state);
state = static_cast<float>(tmp);
}
if (model != Model::XBOX_WIRED && model != Model::XBOX) {
if (!gameController && model != Model::XBOX_WIRED && model != Model::XBOX) {
return state; // no deadzone needed
}
if (state * state + otherState * otherState < 0.1) { // inside deadzone circle?
const auto lengthSquared = state * state + otherState * otherState;
const float DEADZONE_RADIUS = 0.2;
if (lengthSquared < DEADZONE_RADIUS * DEADZONE_RADIUS) { // inside deadzone circle?
return 0;
}

// smooth out transition out of deadzone to 2 * deadzone:
if (lengthSquared < DEADZONE_RADIUS * 2 * DEADZONE_RADIUS * 2) {
float directionVectorInDeadzone = state / std::sqrt(lengthSquared) * DEADZONE_RADIUS;
return (state - directionVectorInDeadzone) * 2;
}

// not a perfect square, but most controllers are returning coordinates outside of a circle:
if (lengthSquared > 1) {
return state / std::sqrt(lengthSquared);
}

return state;
}

Expand Down
6 changes: 4 additions & 2 deletions src/test/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -513,8 +513,10 @@ void testKeys() {
auto circleModelview = jngl::modelview().translate(
{ 530, static_cast<double>(-40 + controllerNr * 110) });
jngl::drawEllipse(circleModelview, circleRadius, circleRadius);
jngl::setColor(255, 255, 255, 255);
jngl::drawCircle(circleModelview.translate(circleRadius * stick), 4);
const double length = boost::qvm::mag(stick);
jngl::drawCircle(circleModelview.translate(circleRadius * stick), 4,
length > 1 ? jngl::Rgba(1, 2 - length, 2 - length, 1)
: 0xffffffff_rgba);
jngl::translate(0, 2 * circleRadius + 10);
}

Expand Down

0 comments on commit 9aee239

Please sign in to comment.