腾讯游戏学院有一篇四叉树优化碰撞检测的文章,不过是js版本的,感觉思路写得挺清晰的,所有想翻译成lua来以备不时之需。
不过翻译过程发现挺多问题的,虽然思路很清晰,但细节照它那样写会有问题,有兴趣的人也可以翻译成其他语言看看是不是有问题。原文地址
以下是代码
module("Rect", package.seeall)
local o
function Rect:New(x,y,width,height,o)
o = o or {}
o.x = x
o.y = y
o.width = width
o.height = height
o.centroid = {x = (x+width)*0.5,y = (y+height)*0.5}
o.maxX = x + o.width
o.maxY = y + o.height
setmetatable(o,{__index = self})
--self:Init(x,y,width,height)
return o
end
function Rect:carve(bounds)
local arr = {}
if bounds.centroid.y > self.y and bounds.centroid.y < self.maxY and bounds.centroid.x > self.x and bounds.centroid.x < self.maxX then
local rect1 = self:New(self.x,self.y,bounds.centroid.x - self.x,bounds.centroid.y - self.y)
local rect2 = self:New(self.x,bounds.centroid.y,bounds.centroid.x - self.x,self.maxY - bounds.centroid.y)
local rect3 = self:New(bounds.centroid.x,self.y,self.maxX - bounds.centroid.x,bounds.centroid.y - self.y)
local rect4 = self:New(bounds.centroid.x,bounds.centroid.y,self.maxX - bounds.centroid.x,self.maxY - bounds.centroid.y)
table.insert(