Last active
December 28, 2024 09:50
-
-
Save Shilo/d63d543e050f8570a4637f9afa0869c8 to your computer and use it in GitHub Desktop.
Godot 4 Node extension for getting Node2D bounding box based on descendents.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
public static partial class Node2DExtension | |
{ | |
public static Rect2 GetCalculatedBounds(this Node2D node2D) | |
{ | |
var rect = new Rect2(); | |
var children = node2D.GetChildren().ToList(); | |
while (children.Count > 0) | |
{ | |
Node child = children[^1]; | |
children.RemoveAt(children.Count - 1); | |
children.AddRange(child.GetChildren()); | |
if (child is not Node2D node2DChild) | |
continue; | |
// Check for Godot get_rect or C# custom GetRect method | |
var rectCallback = node2DChild.HasMethod("get_rect") ? "get_rect" : | |
node2DChild.HasMethod("GetRect") ? "GetRect" : null; | |
if (string.IsNullOrEmpty(rectCallback)) | |
continue; | |
var childRect = (Rect2)node2DChild.Call(rectCallback); | |
childRect.Position = node2D.ToLocal(node2DChild.ToGlobal(childRect.Position)); | |
rect = rect.Merge(childRect); | |
} | |
return rect; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment