JCLib.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. namespace JC.CS
  7. {
  8. public class Utility
  9. {
  10. public static long GetTimestamp()
  11. {
  12. TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
  13. return (long)ts.TotalMilliseconds;
  14. }
  15. }
  16. public class CountLocker
  17. {
  18. int count = 0;
  19. HashSet<object> objects = new HashSet<object>();
  20. public void Lock()
  21. {
  22. count++;
  23. }
  24. public void Unlock()
  25. {
  26. count--;
  27. if (count < 0) count = 0;
  28. }
  29. public bool IsLocked()
  30. {
  31. return count > 0 || objects.Count > 0;
  32. }
  33. public bool IsReleased()
  34. {
  35. return !IsLocked();
  36. }
  37. public void Clear()
  38. {
  39. count = 0;
  40. objects.Clear();
  41. }
  42. }
  43. }
  44. namespace JC.Unity
  45. {
  46. public class TouchChecker
  47. {
  48. bool hasTouch;
  49. int touchID;
  50. bool isTouchOnUI;
  51. public Action<Touch, bool> onBegan;
  52. public Action<Touch, bool> onMoved;
  53. public Action<Touch, bool> onEnded;
  54. public void Update()
  55. {
  56. if (Input.touchCount > 0)
  57. {
  58. if (!hasTouch)
  59. {
  60. Touch touch = Input.GetTouch(0);
  61. if (touch.phase == TouchPhase.Began)
  62. {
  63. hasTouch = true;
  64. touchID = touch.fingerId;
  65. }
  66. }
  67. if (hasTouch) {
  68. Touch touch = default;
  69. bool hasFindTouch = false;
  70. foreach (Touch t in Input.touches)
  71. {
  72. if (t.fingerId == touchID)
  73. {
  74. touch = t;
  75. hasFindTouch = true;
  76. break;
  77. }
  78. }
  79. if (!hasFindTouch)
  80. {
  81. hasTouch = false;
  82. return;
  83. }
  84. bool isOverUI = EventSystem.current.IsPointerOverGameObject(touchID);
  85. if (touch.phase == TouchPhase.Began)
  86. {
  87. isTouchOnUI = isOverUI;
  88. onBegan?.Invoke(touch, isTouchOnUI);
  89. }
  90. else if (touch.phase == TouchPhase.Moved)
  91. {
  92. isTouchOnUI = isOverUI;
  93. onMoved?.Invoke(touch, isTouchOnUI);
  94. }
  95. else if (touch.phase == TouchPhase.Stationary)
  96. {
  97. }
  98. else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
  99. {
  100. hasTouch = false;
  101. //UnityBug,Ended阶段isOverUI总是返回false,因此通过新增变量touchOnUI来辅助识别触点是否在UI上
  102. onEnded?.Invoke(touch, isTouchOnUI);
  103. }
  104. }
  105. }
  106. else
  107. {
  108. hasTouch = false;
  109. }
  110. }
  111. }
  112. }