YSort25D.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Godot;
  2. using System.Collections.Generic;
  3. #if REAL_T_IS_DOUBLE
  4. using real_t = System.Double;
  5. #else
  6. using real_t = System.Single;
  7. #endif
  8. /// <summary>
  9. /// Assigns Z-index values to Node25D children.
  10. /// </summary>
  11. [Tool] // Commented out because it sometimes crashes the editor when running the game...
  12. public class YSort25D : Node // Note: NOT Node2D, Node25D, or YSort
  13. {
  14. /// <summary>
  15. /// Whether or not to automatically call Sort() in _Process().
  16. /// </summary>
  17. [Export]
  18. public bool sortEnabled = true;
  19. public override void _Process(real_t delta)
  20. {
  21. if (sortEnabled)
  22. {
  23. Sort();
  24. }
  25. }
  26. /// <summary>
  27. /// Call this method in _Process, or whenever you want to sort children.
  28. /// </summary>
  29. public void Sort()
  30. {
  31. var children = GetParent().GetChildren();
  32. if (children.Count > 4000)
  33. {
  34. GD.PrintErr("Sorting failed: Max number of YSort25D nodes is 4000.");
  35. }
  36. List<Node25D> node25dChildren = new List<Node25D>();
  37. foreach (Node n in children)
  38. {
  39. if (n is Node25D node25d)
  40. {
  41. node25dChildren.Add(node25d);
  42. }
  43. }
  44. node25dChildren.Sort();
  45. int zIndex = -4000;
  46. for (int i = 0; i < node25dChildren.Count; i++)
  47. {
  48. node25dChildren[i].ZIndex = zIndex;
  49. // Increment by 2 each time, to allow for shadows in-between.
  50. // This does mean that we have a limit of 4000 total sorted Node25Ds.
  51. zIndex += 2;
  52. }
  53. }
  54. }