Lua Love2d 四叉树递归

更新--我找到了答案。事实证明我不擅长数学和二维点的可视化。我没有正确设置南边或东边的细分。

我一直试图在Love2d中制作一个四叉树来跟踪点。我已经编写了大部分代码,但我不认为递归正常工作。

我很新手,所以我真的不知道从哪里开始。

它似乎忽略了进入东南象限的点。

我认为它递归进入插入函数时,它要么查看父点数组,要么似乎没有进入所有插入函数。

local QuadTree = {}
QuadTree.__index = QuadTree
function QuadTree:new(boundary,capacity)
    local quadTemp = {}
    setmetatable(quadTemp, QuadTree)
    if (not boundary) then
        print('没有给出新四叉树的边界')
    end
    if (type(capacity) ~= 'number') then
        print('边界应为数字')
    end
    if (capacity < 1) then
        print('容量应大于一个')
    end
    quadTemp.boundary = boundary
    quadTemp.capacity = capacity
    quadTemp.points = {}
    quadTemp.hasDivided = false
    return quadTemp
end

function QuadTree:insert(p)
    --如果此点不属于这个点,则不添加
    if (not self.boundary:contains(p)) then
        return false
    elseif (#self.points<self.capacity) then
        table.insert(self.points,p)
        return true
    elseif(not self.hasDivided) then
        self:subdivide()
    elseif(self.hasDivided) then
        return self.northeast:insert(p) or
                self.northwest:insert(p) or
                self.southeast:insert(p) or
                self.southwest:insert(p)
    end
end
function QuadTree:subdivide()
    local x = self.boundary.xpos
    local y = self.boundary.ypos
    local w = self.boundary.width / 2
    local h = self.boundary.height / 2

    local nw = Rectangle:new(x,y,w,h)
    self.northwest = QuadTree:new(nw,self.capacity)
    local ne = Rectangle:new(w,y,w,h)
    self.northeast = QuadTree:new(ne,self.capacity)
    local sw = Rectangle:new(x,h,w,h)
    self.southwest = QuadTree:new(sw,self.capacity)
    local se = Rectangle:new(w,h,w,h)
    self.southeast = QuadTree:new(se,self.capacity)
    self.hasDivided = true
end
function QuadTree:query(range,found)
    --如果我们还没有找到任何东西,让我们创建一个列表以防万一
    if (not found) then found = {} end
    --如果此单元格不包含边界,则返回一个空列表
    if (not range:intersects(self.boundary)) then
        return found
    end
    for k,v in pairs(self.points) do
        if (range:contains(v)) then
            table.insert(found,v)
        end
    end
    --如果当前单元格已经分解,我们需要检查它的子元素
    if (self.hasDivided) then
        self.northwest:query(range,found)
        self.northeast:query(range,found)
        self.southwest:query(range,found)
        self.southeast:query(range,found)
    end
    return found;
end
点赞