我正在尝试将四叉树实现到一个小项目中,只是为了练习。我有几个粒子在一个半径内弹跳,并且四叉树绑定到它形成的圆圈。
一切正常,除了我相信我的插入或清除中存在某种泄漏。用 1000 个粒子运行大约 10 秒后,它开始严重滞后。
这里是函数
_subDivisions 是一个数组,_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++;
}
}
}
}