四叉树是一种树状数据结构,在每一个节点上会有四个子区块。四叉树常应用于二维空间资料的分析与分类。
它将资料区分成为四个象限。资料范围可以是方形或矩形或其他任意形状。这种数据结构是由 拉斐尔·芬科尔(Raphael Finkel) 与 J.
L. Bentley 在1974年发展出来 。 类似的资料分割方法也称为 Q-tree。 所有的四叉树法有共同之特点:
1.可分解成为各自的区块
2.每个区块都有节点容量。当节点达到最大容量时,节点分裂
3.树状数据结构依造四叉树法加以区分
以上定义描述引用于wiki链接(四叉树定义),在游戏开发中主要用于大地图资源逻辑管理,粒子碰撞检测等,引入四叉树/八叉树用于二维/三维的空间管理。下面是我用Lua实现的QuadTree类。
local QuadTree = Class("QuadTree")
local Dir = {
LeftBottom = 0, -- 00
LeftTop = 1, -- 01
RightBottom = 2, -- 10
RightTop = 3, -- 11
}
-- centre_x, centre_y, width, height为最大layout
-- capacity为每个节点最多容纳的点容量
local function __init(self, centre_x, centre_y, width, height, capacity)
self.centre_x = centre_x
self.centre_y = centre_y
self.width = width
self.height = height
-- 存放transList
self.transList = {
}
-- 最大容纳trans数量
self.capacity = capacity
-- 是否已被拆分
self.divided = false
-- 子节点
self.children = {
}
end
local function __delete(self)
if self.children and not table.empty(self.children) then
for _, childrenNode in pairs(self.children) do
childrenNode:Delete()
end
end
self.children = nil
self.transList = nil