y_sort_25d.gd 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Sorts all Node25D children of its parent.
  2. # This is different from the C# version of this project
  3. # because the execution order is different and otherwise
  4. # sorting is delayed by one frame.
  5. @tool
  6. @icon("res://addons/node25d/icons/y_sort_25d_icon.png")
  7. extends Node # Note: NOT Node2D, Node25D, or Node2D
  8. class_name YSort25D
  9. # Whether or not to automatically call sort() in _process().
  10. @export var sort_enabled := true
  11. var _parent_node: Node2D # NOT Node25D
  12. func _ready():
  13. _parent_node = get_parent()
  14. func _process(_delta):
  15. if sort_enabled:
  16. sort()
  17. # Call this method in _process, or whenever you want to sort children.
  18. func sort():
  19. if _parent_node == null:
  20. return # _ready() hasn't been run yet
  21. var parent_children = _parent_node.get_children()
  22. if parent_children.size() > 4000:
  23. # The Z index only goes from -4096 to 4096, and we want room for objects having multiple layers.
  24. printerr("Sorting failed: Max number of YSort25D nodes is 4000.")
  25. return
  26. # We only want to get Node25D children.
  27. # Currently, it also grabs Node2D children.
  28. var node25d_nodes = []
  29. for n in parent_children:
  30. if n.get_class() == "Node2D":
  31. node25d_nodes.append(n)
  32. node25d_nodes.sort_custom(Callable(Node25D, &"y_sort_slight_xz"))
  33. var z_index = -4000
  34. for i in range(0, node25d_nodes.size()):
  35. node25d_nodes[i].z_index = z_index
  36. # Increment by 2 each time, to allow for shadows in-between.
  37. # This does mean that we have a limit of 4000 total sorted Node25Ds.
  38. z_index += 2