Skip to content

Instantly share code, notes, and snippets.

@TORISOUP
Created February 2, 2015 10:18
Show Gist options
  • Save TORISOUP/c8c5fd66067dcd9d71d0 to your computer and use it in GitHub Desktop.
Save TORISOUP/c8c5fd66067dcd9d71d0 to your computer and use it in GitHub Desktop.
memo
using UnityEngine;
using System.Collections;
using UniRx;
using System.Linq;
public class Command : MonoBehaviour
{
enum InputStatus
{
None,
Up,
Down,
Left,
Right,
UpRight,
UpLeft,
DownRight,
DownLeft,
A_Button,
B_Button
}
void Start()
{
var horizontalObservable = Observable.EveryUpdate().Select(_ => Input.GetAxisRaw("Horizontal"));
var verticalObservable = Observable.EveryUpdate().Select(_ => Input.GetAxisRaw("Vertical"));
var joystickObservable = Observable.Zip(horizontalObservable, verticalObservable, (h, v) =>
{
return ConvertVector2ToInputStatus(new Vector2(h, v));
})
.DistinctUntilChanged()
.Where(x => x != InputStatus.None);
var AButtonObservable = Observable.EveryUpdate().Where(_ => Input.GetButtonDown("A Button")).Select(_ => InputStatus.A_Button);
var BButtonObservable = Observable.EveryUpdate().Where(_ => Input.GetButtonDown("B Button")).Select(_ => InputStatus.B_Button);
Observable
.Merge(AButtonObservable, BButtonObservable, joystickObservable);
}
InputStatus ConvertVector2ToInputStatus(Vector2 input)
{
if (input.sqrMagnitude <= 0.01f)
{
return InputStatus.None;
}
var normalizedInput = input.normalized;
if (Vector2.Angle(normalizedInput, Vector2.up + Vector2.right) <= 45)
{
return InputStatus.UpRight;
}
if (Vector2.Angle(normalizedInput, Vector2.up - Vector2.right) <= 45)
{
return InputStatus.UpLeft;
}
if (Vector2.Angle(normalizedInput, -Vector2.up + Vector2.right) <= 45)
{
return InputStatus.DownRight;
}
if (Vector2.Angle(normalizedInput, -Vector2.up - Vector2.right) <= 45)
{
return InputStatus.DownLeft;
}
if (Vector2.Angle(normalizedInput, Vector2.up) <= 45)
{
return InputStatus.Up;
}
if (Vector2.Angle(normalizedInput, -Vector2.up) <= 45)
{
return InputStatus.Down;
}
if (Vector2.Angle(normalizedInput, Vector2.right) <= 45)
{
return InputStatus.Right;
}
if (Vector2.Angle(normalizedInput, -Vector2.right) <= 45)
{
return InputStatus.Left;
}
return InputStatus.None;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment