/* * 分割,四叉树的核心来了 * * 分割就是先把这个节点的范围分成四份,分别给四个子节点,之后把这个节点里的所有叶子按位置存进四个子节点里。 * 分割完成后这个节点就从树梢变成了树枝,而四个子节点成为了新的树梢。 */ void Split() { Debug.Log("位置在(" + _field.top + "," + _field.right + "," + _field.bottom + "," + _field.left + ")的树梢节点达到分割条件,进行分割"); //计算出横竖的中心坐标 float xCenter = (_field.left + _field.right) / 2; float yCenter = (_field.bottom + _field.top) / 2; //用上面计算的中心坐标和原本的区域组合出四个子节点的区域来,并且把最大叶子数、最小宽高一起传给子节点 _upperRightChild = new QuadtreeBasic <T>(_field.top, _field.right, yCenter, xCenter, _maxLeafsNumber, _minSideLength); _lowerRightChild = new QuadtreeBasic <T>(yCenter, _field.right, _field.bottom, xCenter, _maxLeafsNumber, _minSideLength); _lowerLeftChild = new QuadtreeBasic <T>(yCenter, xCenter, _field.bottom, _field.left, _maxLeafsNumber, _minSideLength); _upperLeftChild = new QuadtreeBasic <T>(_field.top, xCenter, yCenter, _field.left, _maxLeafsNumber, _minSideLength); //生成完子节点后把这个节点里的所有叶子分给子节点 foreach (QuadtreeBasicLeaf <T> leaf in _leafs) //假设你不会用 foreach ,请看 QuadtreeBasicDetector { SetLeafToChildren(leaf); } _leafs = null; //将叶子分给子节点后这个节点就不需要继续保留叶子了,把叶子List设为null,让C#的清理器来清理掉节省内存 }
static QuadtreeBasic <GameObject> _quadtree; //static方法必须要static变量,所以这里设为static private void Awake() { _quadtree = new QuadtreeBasic <GameObject>(_top, _right, _bottom, _left, _maxLeafsNumber, _minSideLength); }