Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using Smooth.Foundations.PatternMatching.GeneralMatcher;
- using UniRx;
- using UnityEngine;
- public enum SwipeDirection
- {
- Up,
- Down,
- Left,
- Right
- }
- public class Swipe : MonoBehaviour
- {
- public static IObservable<SwipeDirection> SwipeStream => _swipeSubject;
- private static readonly Subject<SwipeDirection> _swipeSubject = new Subject<SwipeDirection>();
- private void Awake()
- {
- var baseStream = Observable
- // Do on every update.
- .EveryUpdate()
- // Until this component will be destroyed.
- .TakeUntilDestroy(this)
- // Only when component is enabled and gameObject is active in hierarchy.
- .Where(_ => enabled && gameObject.activeInHierarchy);
- // All that was mentioned in baseStream.
- var onMouseDownStream = baseStream
- // When left mouse button is pressed.
- .Where(_ => Input.GetMouseButtonDown(0))
- // Save its position.
- .Select(_ => (Vector2) Input.mousePosition);
- // All that was mentioned in baseStream.
- var onMouseUpStream = baseStream
- // When left mouse button is released.
- .Where(_ => Input.GetMouseButtonUp(0))
- // Save its position.
- .Select(_ => (Vector2) Input.mousePosition);
- var swipeDirectionStream = Observable
- // Combine into the tuple values that will be emitted by onMouseDownStream and onMouseUpStream streams.
- .Zip(onMouseDownStream, onMouseUpStream, Tuple.Create)
- // Get vector that represents swipe direction.
- .Select(firstAndSecondPos => (firstAndSecondPos.Item2 - firstAndSecondPos.Item1).normalized)
- // Check that first mouse press position are not equal to release position so the length of swipe direction
- // vector must be greater than 0.
- .Where(dir => dir.magnitude > 0f)
- // Match the direction vector to enum parameter that represents it.
- .Select(swipeDirection => swipeDirection.Match().To<SwipeDirection>()
- .Where(swipe => swipe.y > 0 && Mathf.Abs(swipe.x) <= 0.7f).Return(SwipeDirection.Up)
- .Where(swipe => swipe.y < 0 && Mathf.Abs(swipe.x) <= 0.7f).Return(SwipeDirection.Down)
- .Where(swipe => swipe.x < 0 && Mathf.Abs(swipe.y) <= 0.7f).Return(SwipeDirection.Left)
- .Where(swipe => swipe.x > 0 && Mathf.Abs(swipe.y) <= 0.7f).Return(SwipeDirection.Right)
- .Result())
- // Finally emit the swipe direction by the subject.
- .Do(direction => _swipeSubject.OnNext(direction));
- }
- }
Add Comment
Please, Sign In to add comment