Skip to content

Instantly share code, notes, and snippets.

@CAD97
Last active January 23, 2016 20:32
Show Gist options
  • Save CAD97/7b0f7440e911f804cd4e to your computer and use it in GitHub Desktop.
Save CAD97/7b0f7440e911f804cd4e to your computer and use it in GitHub Desktop.
Better input for Unity C#
using System;
using UnityEngine;
namespace cad97.BetterInput
{
public class Smart2DInput
{
public static float Deadzone { get; set; }
public static JoystickDeadzoneStyle DeadzoneStyle { get; set; }
public static Vector2 Get() { return Get(Joystick2D.DEFAULT); }
public static Vector2 Get(Joystick2D stick)
{
Vector2 input = new Vector2(stick.X(), stick.Y());
input = Zone(input);
return input;
}
private static Vector2 Zone(Vector2 v)
{
// Scaled deadzone
float deadX = Mathf.Lerp(0f, Deadzone, v.y);
float deadY = Mathf.Lerp(0f, Deadzone, v.x);
switch (DeadzoneStyle)
{
case JoystickDeadzoneStyle.NONE:
break;
case JoystickDeadzoneStyle.AXIAL:
if (Mathf.Abs(v.x) < Deadzone) v.x = 0f;
if (Mathf.Abs(v.y) < Deadzone) v.y = 0f;
break;
case JoystickDeadzoneStyle.RADIAL:
if (v.magnitude < Deadzone) v = Vector2.zero;
break;
case JoystickDeadzoneStyle.LINEAR_RESCALED_RADIAL:
if (v.magnitude < Deadzone) v = Vector2.zero;
else v = Vector2.Lerp(v, v.normalized, v.magnitude - Deadzone);
break;
case JoystickDeadzoneStyle.BOWTIE:
if (v.magnitude < Deadzone) v = Vector2.zero;
if (Mathf.Abs(v.x) < deadX) v.x = 0f;
if (Mathf.Abs(v.y) < deadY) v.y = 0f;
break;
case JoystickDeadzoneStyle.LINEAR_RESCALED_BOWTIE:
if (v.magnitude < Deadzone) v = Vector2.zero;
else Vector2.Lerp(v, v.normalized, v.magnitude - Deadzone);
if (Mathf.Abs(v.x) < deadX) v.x = 0f;
if (Mathf.Abs(v.y) < deadY) v.y = 0f;
break;
default:
Debug.LogErrorFormat("{0} is not a viable DeadzoneStyle. No deadzone was applied.", DeadzoneStyle);
break;
}
return v;
}
}
[Serializable]
public struct Joystick2D
{
public readonly Func<float> X;
public readonly Func<float> Y;
public Joystick2D(Func<float> xAxisGet, Func<float> yAxisGet)
{
X = xAxisGet; Y = yAxisGet;
}
public static readonly Joystick2D DEFAULT = new Joystick2D(() => Input.GetAxisRaw("Horizontal"), () => Input.GetAxisRaw("Vertical"));
}
[Serializable]
public enum JoystickDeadzoneStyle
{
NONE, AXIAL, RADIAL, LINEAR_RESCALED_RADIAL, BOWTIE, LINEAR_RESCALED_BOWTIE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment