Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / manager / DragUiManager.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using Godot;
  4.  
  5. public static class DragUiManager
  6. {
  7. private static readonly List<DragBinder> _list = new List<DragBinder>();
  8. private static readonly List<DragBinder> _removeList = new List<DragBinder>();
  9. private static readonly List<DragBinder> _addList = new List<DragBinder>();
  10. /// <summary>
  11. /// 绑定拖拽事件
  12. /// </summary>
  13. public static DragBinder BindDrag(Control control, StringName inputAction, Action<DragState, Vector2> callback)
  14. {
  15. var binder = new DragBinder();
  16. binder.Control = control;
  17. control.MouseEntered += binder.OnMouseEntered;
  18. control.MouseExited += binder.OnMouseExited;
  19. binder.Callback = callback;
  20. binder.InputAction = inputAction;
  21. _addList.Add(binder);
  22. return binder;
  23. }
  24. /// <summary>
  25. /// 绑定拖拽事件
  26. /// </summary>
  27. public static DragBinder BindDrag(Control control, Action<DragState, Vector2> callback)
  28. {
  29. return BindDrag(control, "mouse_left", callback);
  30. }
  31.  
  32. /// <summary>
  33. /// 解绑拖拽事件
  34. /// </summary>
  35. public static void UnBindDrag(DragBinder binder)
  36. {
  37. if (!_removeList.Contains(binder))
  38. {
  39. _removeList.Add(binder);
  40. }
  41. }
  42.  
  43. public static void Update(float delta)
  44. {
  45. //更新拖拽位置
  46. if (_list.Count > 0)
  47. {
  48. foreach (var dragBinder in _list)
  49. {
  50. if (dragBinder.Dragging && !Input.IsActionPressed(dragBinder.InputAction)) //松开鼠标, 结束拖拽
  51. {
  52. dragBinder.Dragging = false;
  53. dragBinder.Callback(DragState.DragEnd, Vector2.Zero);
  54. }
  55. else if (!dragBinder.Dragging) //开始拖拽
  56. {
  57. if (dragBinder.MouseEntered && Input.IsActionJustPressed(dragBinder.InputAction))
  58. {
  59. dragBinder.Dragging = true;
  60. dragBinder.PrevPosition = dragBinder.Control.GetGlobalMousePosition();
  61. dragBinder.Callback(DragState.DragStart, Vector2.Zero);
  62. }
  63. }
  64. else //拖拽更新
  65. {
  66. var mousePos = dragBinder.Control.GetGlobalMousePosition();
  67. if (mousePos != dragBinder.PrevPosition)
  68. {
  69. var deltaPosition = mousePos - dragBinder.PrevPosition;
  70. dragBinder.PrevPosition = mousePos;
  71. dragBinder.Callback(DragState.DragMove, deltaPosition);
  72. }
  73. }
  74. }
  75. }
  76.  
  77. //移除绑定
  78. if (_removeList.Count > 0)
  79. {
  80. foreach (var binder in _removeList)
  81. {
  82. if (_list.Remove(binder) && GodotObject.IsInstanceValid(binder.Control))
  83. {
  84. binder.Control.MouseEntered -= binder.OnMouseEntered;
  85. binder.Control.MouseExited -= binder.OnMouseExited;
  86. }
  87. }
  88. _removeList.Clear();
  89. }
  90. //添加绑定
  91. if (_addList.Count > 0)
  92. {
  93. _list.AddRange(_addList);
  94. _addList.Clear();
  95. }
  96. }
  97. }