Skip to content

Instantly share code, notes, and snippets.

@shiena
Last active August 9, 2021 18:43
Show Gist options
  • Save shiena/faa5ab3cf661dcd73cecc6757a2019b3 to your computer and use it in GitHub Desktop.
Save shiena/faa5ab3cf661dcd73cecc6757a2019b3 to your computer and use it in GitHub Desktop.
[Unity] UniRxを使ってアナログスティックで十字キーのGetKeyDownをエミュレートする
using System.Collections.Generic;
using UniRx;
using UniRx.Triggers;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
private enum DPadDirection
{
None,
Up,
Down,
Left,
Right,
UpRight,
UpLeft,
DownRight,
DownLeft,
}
private const float Threshold = 0.3f;
// 4方向にエミュレートするので4で割る
private const float Direct4 = 360f / 4;
private static readonly IReadOnlyDictionary<int, DPadDirection> DirectionMap4 = new Dictionary<int, DPadDirection>()
{
{0, DPadDirection.Right},
{4 / 4, DPadDirection.Up},
{4 / 2, DPadDirection.Left},
{4 / -4, DPadDirection.Down},
{4 / -2, DPadDirection.Left},
};
// 8方向にエミュレートするので8で割る
private const float Direct8 = 360f / 8;
private static readonly IReadOnlyDictionary<int, DPadDirection> DirectionMap8 = new Dictionary<int, DPadDirection>()
{
{0, DPadDirection.Right},
{8 / 4, DPadDirection.Up},
{8 / 2, DPadDirection.Left},
{8 / -4, DPadDirection.Down},
{8 / -2, DPadDirection.Left},
{1, DPadDirection.UpRight},
{3, DPadDirection.UpLeft},
{-1, DPadDirection.DownRight},
{-3, DPadDirection.DownLeft},
};
private DPadDirection GetDirection(float nums, IReadOnlyDictionary<int, DPadDirection> map)
{
// references
// - https://forum.unity.com/threads/8-way-direction-joystick-only.438758/#post-3513040
// - https://stickpan.hatenablog.com/entry/2014/05/13/172026
var result = DPadDirection.None;
var inputDirection = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (inputDirection.magnitude >= Threshold)
{
var angle = Mathf.Atan2(inputDirection.y, inputDirection.x) * Mathf.Rad2Deg;
var direction = Mathf.RoundToInt(angle / nums);
map.TryGetValue(direction, out result);
}
return result;
}
private DPadDirection GetDirection4()
{
return GetDirection(Direct4, DirectionMap4);
}
private DPadDirection GetDirection8()
{
return GetDirection(Direct8, DirectionMap8);
}
private void Start()
{
// 4分割の場合
this.UpdateAsObservable()
.Select(_ => GetDirection4())
.DistinctUntilChanged()
.Where(d => d != DPadDirection.None)
.Subscribe(d => { Debug.Log(d); })
.AddTo(gameObject);
// 8分割の場合
this.UpdateAsObservable()
.Select(_ => GetDirection8())
.DistinctUntilChanged()
.Where(d => d != DPadDirection.None)
.Subscribe(d => { Debug.Log(d); })
.AddTo(gameObject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment