Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created September 18, 2019 12:52
Show Gist options
  • Save DataGreed/c7c7c15d2cf009bc63966e60f44be522 to your computer and use it in GitHub Desktop.
Save DataGreed/c7c7c15d2cf009bc63966e60f44be522 to your computer and use it in GitHub Desktop.
Implements proper deadzones for joystick or gamepad sticks for Unity
using UnityEngine;
namespace datagreed.input
{
/// <summary>
/// Implements proper deadzones for joystick or gamepad sticks.
/// Based on http://www.third-helix.com/2013/04/12/doing-thumbstick-dead-zones-right.html
///
/// Example usage:
///
/// Vector2 movementInput = JoystickDeadZone.InputWithRadialDeadZone(
/// Input.GetAxis("Horizontal"),
/// Input.GetAxis("Vertical")
/// );
///
/// </summary>
public class JoystickDeadZone
{
public const float defaultDeadzone = 0.25f;
/// <summary>
/// Returns joystick input with proper radial deadzone.
/// </summary>
/// <param name="horizontalInput"></param>
/// <param name="verticalInput"></param>
/// <param name="deadzone"></param>
/// <returns></returns>
public static Vector2 InputWithRadialDeadZone(float horizontalInput, float verticalInput, float deadzone=defaultDeadzone)
{
Vector2 joystickInput = new Vector2(horizontalInput, verticalInput);
if(joystickInput.magnitude < deadzone) joystickInput = Vector2.zero;
return joystickInput;
}
/// <summary>
/// Returns joystick input with scaled radial deadzone, that feels like accceleration.
/// Good when high precision is needed
/// </summary>
/// <param name="horizontalInput"></param>
/// <param name="verticalInput"></param>
/// <param name="deadzone"></param>
/// <returns></returns>
public static Vector2 InputWithScaledRadialDeadZone(float horizontalInput, float verticalInput,
float deadzone = defaultDeadzone)
{
Vector2 joystickInput = new Vector2(horizontalInput, verticalInput);
if(joystickInput.magnitude < deadzone)
joystickInput = Vector2.zero;
else
joystickInput = joystickInput.normalized * ((joystickInput.magnitude - deadzone) / (1 - deadzone));
return joystickInput;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment