Guest User

Untitled

a guest
Jun 25th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. using System;
  2. using Smooth.Foundations.PatternMatching.GeneralMatcher;
  3. using UniRx;
  4. using UnityEngine;
  5.  
  6. public enum SwipeDirection
  7. {
  8. Up,
  9. Down,
  10. Left,
  11. Right
  12. }
  13.  
  14. public class Swipe : MonoBehaviour
  15. {
  16. public static IObservable<SwipeDirection> SwipeStream => _swipeSubject;
  17. private static readonly Subject<SwipeDirection> _swipeSubject = new Subject<SwipeDirection>();
  18.  
  19. private void Awake()
  20. {
  21. var baseStream = Observable
  22. // Do on every update.
  23. .EveryUpdate()
  24. // Until this component will be destroyed.
  25. .TakeUntilDestroy(this)
  26. // Only when component is enabled and gameObject is active in hierarchy.
  27. .Where(_ => enabled && gameObject.activeInHierarchy);
  28.  
  29. // All that was mentioned in baseStream.
  30. var onMouseDownStream = baseStream
  31. // When left mouse button is pressed.
  32. .Where(_ => Input.GetMouseButtonDown(0))
  33. // Save its position.
  34. .Select(_ => (Vector2) Input.mousePosition);
  35.  
  36. // All that was mentioned in baseStream.
  37. var onMouseUpStream = baseStream
  38. // When left mouse button is released.
  39. .Where(_ => Input.GetMouseButtonUp(0))
  40. // Save its position.
  41. .Select(_ => (Vector2) Input.mousePosition);
  42.  
  43. var swipeDirectionStream = Observable
  44. // Combine into the tuple values that will be emitted by onMouseDownStream and onMouseUpStream streams.
  45. .Zip(onMouseDownStream, onMouseUpStream, Tuple.Create)
  46. // Get vector that represents swipe direction.
  47. .Select(firstAndSecondPos => (firstAndSecondPos.Item2 - firstAndSecondPos.Item1).normalized)
  48. // Check that first mouse press position are not equal to release position so the length of swipe direction
  49. // vector must be greater than 0.
  50. .Where(dir => dir.magnitude > 0f)
  51. // Match the direction vector to enum parameter that represents it.
  52. .Select(swipeDirection => swipeDirection.Match().To<SwipeDirection>()
  53. .Where(swipe => swipe.y > 0 && Mathf.Abs(swipe.x) <= 0.7f).Return(SwipeDirection.Up)
  54. .Where(swipe => swipe.y < 0 && Mathf.Abs(swipe.x) <= 0.7f).Return(SwipeDirection.Down)
  55. .Where(swipe => swipe.x < 0 && Mathf.Abs(swipe.y) <= 0.7f).Return(SwipeDirection.Left)
  56. .Where(swipe => swipe.x > 0 && Mathf.Abs(swipe.y) <= 0.7f).Return(SwipeDirection.Right)
  57. .Result())
  58. // Finally emit the swipe direction by the subject.
  59. .Do(direction => _swipeSubject.OnNext(direction));
  60. }
  61. }
Add Comment
Please, Sign In to add comment