C# 四叉树最终开始导致延迟

C# 四叉树最终开始导致延迟,c#,xna,quadtree,C#,Xna,Quadtree,我正试图在一个小项目中实现一个四叉树,只是为了练习。我有几个粒子在半径范围内反弹,一棵四叉树被绑定到它形成的圆上 一切正常,除了我认为我的插入或清除有某种泄漏。在使用1000个粒子运行约10秒后,它开始严重滞后 下面是函数 _细分是一个数组,\u drawableGameObjects是一个列表 public void Clear() { _drawableGameObjects.Clear(); if (_subDivisions != null)

我正试图在一个小项目中实现一个四叉树,只是为了练习。我有几个粒子在半径范围内反弹,一棵四叉树被绑定到它形成的圆上

一切正常,除了我认为我的插入或清除有某种泄漏。在使用1000个粒子运行约10秒后,它开始严重滞后

下面是函数

_细分是一个数组,\u drawableGameObjects是一个列表

public void Clear()
    {
        _drawableGameObjects.Clear();

        if (_subDivisions != null)
            foreach (QuadTree quad in _subDivisions)
                quad.Clear();

        _subDivisions = null;
    }


public void Insert(DrawableGameObject drawableGameObject)
    {
        if (_subDivisions != null)
        {
            int index = GetIndex(drawableGameObject);

            if (index > -1)
                _subDivisions[index].Insert(drawableGameObject);

            return;
        }

        _drawableGameObjects.Add(drawableGameObject);

        if (_drawableGameObjects.Count > _maxObjects && _level < _maximumLevel)
        {
            Subdivide();

            int i = 0;
            while (i < _drawableGameObjects.Count)
            {
                int index = GetIndex(_drawableGameObjects[i]);
                if (index > -1)
                {
                    DrawableGameObject currentObject = _drawableGameObjects[i];
                    _subDivisions[index].Insert(currentObject);
                    _drawableGameObjects.Remove(currentObject);
                }
                else
                {
                    i++;
                }
            }
        }
    }
public void Clear()
{
_drawableGameObjects.Clear();
如果(_细分!=null)
foreach(四叉树四叉树在_细分中)
quad.Clear();
_细分=空;
}
公共空白插入(DrawableGameObject DrawableGameObject)
{
如果(_细分!=null)
{
int index=GetIndex(drawableGameObject);
如果(索引>-1)
_细分[索引]。插入(drawableGameObject);
返回;
}
_添加(drawableGameObject);
如果(_drawableGameObjects.Count>_maxObjects&&u level<_maximumLevel)
{
细分();
int i=0;
而(i<\u drawableGameObjects.Count)
{
int index=GetIndex(_drawableGameObjects[i]);
如果(索引>-1)
{
drawableGameObjects currentObject=_drawableGameObjects[i];
_细分[索引]。插入(currentObject);
_drawableGameObjects.Remove(当前对象);
}
其他的
{
i++;
}
}
}
}

我发现了问题,但我忘记了这段代码


除了四叉树功能外,我还跟踪游戏层中的每个四叉树。因此,四边形既是其父四边形的子四边形,也是游戏层的子四边形。当我删除四元组时,我是从它们的父四元组中清除它们,而不是从它们的父游戏层中清除它们。

很难理解像这样转储的代码会发生什么。我以前在C#中实现过一个四叉树,如果它有用的话,你可以看看它。我记得有一次我遇到了一个类似于你的四叉树的问题。如果我记得原因,我会告诉你的。还有一件值得一提的事情——在大多数情况下,使用我也实现的哈希表更容易、更快。我相信您会注意到,四叉树可能很难调试,最小的问题将破坏您所有的代码。如果您决定使用四叉树,请编写大量的单元测试来测试代码的每一部分,以确保它对您有效,而不是对您不利。