TouchHelper.gd 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # This will track the position of every pointer in its public `state` property, which is a
  2. # Dictionary, in which each key is a pointer id (integer) and each value its position (Vector2).
  3. # It works by listening to input events not handled by other means.
  4. # It also remaps the pointer indices coming from the OS to the lowest available to be friendlier.
  5. # It can be conveniently setup as a singleton.
  6. extends Node
  7. var state = {}
  8. var _os2own = {}
  9. func _unhandled_input(event):
  10. if event is InputEventScreenTouch:
  11. if event.pressed:
  12. # Down
  13. if !_os2own.has(event.index): # Defensively discard index if already known
  14. var ptr_id = _find_free_pointer_id()
  15. state[ptr_id] = event.position
  16. _os2own[event.index] = ptr_id
  17. else:
  18. # Up
  19. if _os2own.has(event.index): # Defensively discard index if not known
  20. var ptr_id = _os2own[event.index]
  21. state.erase(ptr_id)
  22. _os2own.erase(event.index)
  23. return true
  24. elif event is InputEventScreenDrag:
  25. # Move
  26. if _os2own.has(event.index): # Defensively discard index if not known
  27. var ptr_id = _os2own[event.index]
  28. state[ptr_id] = event.position
  29. return true
  30. return false
  31. func _find_free_pointer_id():
  32. var used = state.keys()
  33. var i = 0
  34. while i in used:
  35. i += 1
  36. return i