| 10 | namespace { |
| 11 | |
| 12 | void ScaleJoystickAxes(float *x, float *y, float deadzone) |
| 13 | { |
| 14 | //radial and scaled dead_zone |
| 15 | //http://www.third-helix.com/2013/04/12/doing-thumbstick-dead-zones-right.html |
| 16 | //input values go from -32767.0...+32767.0, output values are from -1.0 to 1.0; |
| 17 | |
| 18 | if (deadzone == 0) { |
| 19 | return; |
| 20 | } |
| 21 | if (deadzone >= 1.0) { |
| 22 | *x = 0; |
| 23 | *y = 0; |
| 24 | return; |
| 25 | } |
| 26 | |
| 27 | const float maximum = 32767.0f; |
| 28 | float analog_x = *x; |
| 29 | float analog_y = *y; |
| 30 | float dead_zone = deadzone * maximum; |
| 31 | |
| 32 | float magnitude = sqrtf(analog_x * analog_x + analog_y * analog_y); |
| 33 | if (magnitude >= dead_zone) { |
| 34 | // find scaled axis values with magnitudes between zero and maximum |
| 35 | float scalingFactor = 1.0 / magnitude * (magnitude - dead_zone) / (maximum - dead_zone); |
| 36 | analog_x = (analog_x * scalingFactor); |
| 37 | analog_y = (analog_y * scalingFactor); |
| 38 | |
| 39 | // clamp to ensure results will never exceed the max_axis value |
| 40 | float clamping_factor = 1.0f; |
| 41 | float abs_analog_x = fabs(analog_x); |
| 42 | float abs_analog_y = fabs(analog_y); |
| 43 | if (abs_analog_x > 1.0 || abs_analog_y > 1.0) { |
| 44 | if (abs_analog_x > abs_analog_y) { |
| 45 | clamping_factor = 1 / abs_analog_x; |
| 46 | } else { |
| 47 | clamping_factor = 1 / abs_analog_y; |
| 48 | } |
| 49 | } |
| 50 | *x = (clamping_factor * analog_x); |
| 51 | *y = (clamping_factor * analog_y); |
| 52 | } else { |
| 53 | *x = 0; |
| 54 | *y = 0; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | } // namespace |
| 59 | |