Love2d中的矩形碰撞系统无法正常工作。

我正在尝试在Love2d框架中创建管理对象和碰撞的基本架构,所有对象都存储在一个表中(objects:activeObjects) ,然后在objects:calculateCollisions()函数中的循环中遍历所有对象。每次迭代,另一个嵌套循环都会检查该对象是否与同一表中的任何其他对象重叠。在objects:calculateCollisions()的末尾,每个对象理想上都会有一个包含当前时间点上它与之重叠的所有对象引用的表。但是,对象始终具有空的碰撞表。

现在有两个测试对象:一个跟随鼠标移动,一个始终保留在右上角。当它们重叠时,两个对象应该同时消失,但是,如上所述,collidingObjects表始终为空。

我有三个源文件:

main.lua

http://pastebin.com/xuGBSv2j

objects.lua(其中大部分重要内容都写在这里,这可能也是问题所在):

http://pastebin.com/sahB6GF6

customObjects.lua(定义了两个测试对象的构造函数):

function objects:newCollidingObject(x, y)
    local result = self:newActiveObject(x, y, 50, 50)
    result.id = "collidingObject"
    function result:collide(other)
        if other.id == "collidingObject" then self.remove = true end
    end
    return result
end
function objects:newMovingObject(x, y)
    local result = self:newCollidingObject(x, y)
    function result:act()
        self.x = love.mouse.getX()
        self.y = love.mouse.getY()
    end
    return result
end

抱歉,我无法发布超过两个超链接。

编辑:经过更多的调试,我已经将问题缩小到了collidesWith(obj)函数。它似乎总是返回false。

以下是代码:

function result:collidesWith(obj)
    if self.bottom < obj.top then return false end
    if self.top > obj.bottom then return false end
    if self.right < obj.left then return false end
    if self.left > obj.right then return false end
    return true
end
点赞
用户1419479
用户1419479

请通过几个不同的测试输入,用纸笔追踪逻辑。您很快就会发现,您的逻辑是无意义的。你错过了一半的测试,你的一些比较是“指向错误的方向”,等等。所以:

function result:collidesWith(obj)
    if self.bottom <= obj.top and self.bottom >= obj.bottom then return true end
    if self.top >= obj.bottom and self.top <= obj.top then return true end
    if self.right >= obj.left and self.right <= obj.right then return false end
    if self.left <= obj.right and self.left >= obj.left then return false end
    return false
end

这样做是行得通的。

2013-01-13 14:11:25