using System.Collections.Generic;
using System.Threading.Tasks;
using Godot;
namespace ColdMint.scripts.utils;
public class NodeUtils
{
///
/// Delete all child nodes
/// 删除所有子节点
///
///
public static int DeleteAllChild(Node parent)
{
var deleteNumber = 0;
var count = parent.GetChildCount();
if (count <= 0) return deleteNumber;
for (var i = 0; i < count; i++)
{
var node = parent.GetChild(0);
parent.RemoveChild(node);
node.QueueFree();
deleteNumber++;
}
return deleteNumber;
}
///
/// All child nodes are removed asynchronously
/// 异步删除所有子节点
///
///
///
public static async Task DeleteAllChildAsync(Node parent)
{
return await Task.Run(() => DeleteAllChild(parent));
}
///
/// Gets the node closest to the origin
/// 获取距离原点最近的节点
///
///
///origin
///原点
///
///
///Node array
///节点数组
///
///
///Which nodes are excluded
///排除哪些节点
///
///
///Whether or not unseen nodes should be excluded
///是否排除不可见的节点
///
///
public static Node2D? GetTheNearestNode(Node2D origin, Node[] array, HashSet? exclude = null,
bool excludeInvisibleNodes = true)
{
var closestDistance = float.MaxValue;
Node2D? closestNode = null;
foreach (var node in array)
{
if (node is not Node2D node2D) continue;
if (excludeInvisibleNodes && !node2D.Visible)
{
//If invisible nodes are excluded and the current node is invisible, then the next.
//如果排除不可见的节点,且当前节点就是不可见的,那么下一个。
continue;
}
if (exclude != null && exclude.Contains(node))
{
//If the current node, is within our exclusion project. So the next one.
//如果当前节点,在我们的排除项目内。那么下一个。
continue;
}
var distance = node2D.GlobalPosition - origin.GlobalPosition;
var distanceLength = distance.Length();
if (distanceLength < closestDistance)
{
closestDistance = distanceLength;
closestNode = node2D;
}
}
return closestNode;
}
}