Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class SwipeController : MonoBehaviour
- {
- bool isDragging, isMobilePlatform;
- Vector2 tapPoint, SwipeDelta;
- float minSwipeDelta = 130;
- float mSwipeStartTime;
- public float deltaTime;
- public enum SwipeType
- {
- LEFT,
- RIGHT,
- UP,
- DOWN
- }
- public delegate void OnSwipeInput(SwipeType type);
- public static event OnSwipeInput SwipeEvent;
- private void Awake()
- {
- #if UNITY_EDITOR || UNITY_STANDALONE
- isMobilePlatform = false;
- #else
- isMobilePlatform = true;
- #endif
- }
- private void Update()
- {
- if (!isMobilePlatform)
- {
- if (Input.GetMouseButtonDown(0))
- {
- isDragging = true;
- tapPoint = Input.mousePosition;
- mSwipeStartTime = Time.time;
- }
- else if (Input.GetMouseButtonUp(0))
- {
- deltaTime = Time.time - mSwipeStartTime;
- ResetSwipe();
- }
- }
- else
- {
- if (Input.touchCount > 0)
- {
- if (Input.touches[0].phase == TouchPhase.Began)
- {
- isDragging = true;
- tapPoint = Input.touches[0].position;
- mSwipeStartTime = Time.time;
- }
- else if (Input.touches[0].phase == TouchPhase.Canceled ||
- Input.touches[0].phase == TouchPhase.Ended)
- {
- deltaTime = Time.time - mSwipeStartTime;
- ResetSwipe();
- }
- }
- }
- CalculateSwipe();
- }
- void CalculateSwipe()
- {
- SwipeDelta = Vector2.zero;
- if (isDragging)
- {
- if (!isMobilePlatform && Input.GetMouseButton(0))
- SwipeDelta = (Vector2)Input.mousePosition - tapPoint;
- else if (Input.touchCount > 0)
- SwipeDelta = Input.touches[0].position - tapPoint;
- }
- if (SwipeDelta.magnitude > minSwipeDelta)
- {
- if (SwipeEvent != null)
- {
- if (Mathf.Abs(SwipeDelta.x) > Mathf.Abs(SwipeDelta.y))
- SwipeEvent(SwipeDelta.x < 0 ? SwipeType.LEFT : SwipeType.RIGHT);
- else
- SwipeEvent(SwipeDelta.y > 0 ? SwipeType.UP : SwipeType.DOWN);
- }
- ResetSwipe();
- }
- }
- void ResetSwipe()
- {
- isDragging = false;
- tapPoint = SwipeDelta = Vector2.zero;
- mSwipeStartTime = deltaTime = 0f;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement