【问题标题】:Rectangular collision system not working in love2d矩形碰撞系统在love2d中不起作用
【发布时间】:2012-09-02 10:45:00
【问题描述】:

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

现在有两个测试对象:一个随鼠标移动,一个始终停留在右上角。对用户而言,这两个对象在重叠时应该同时消失,但是,如前所述,collidingObjects 表始终为空。

我有三个源文件:
main.lua:
http://pastebin.com/xuGBSv2j
objects.lua(大部分重要的东西都写在这里,可能问题出在哪里):
http://pastebin.com/sahB6GF6customObjects.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

【问题讨论】:

  • 您确定这些属性有效吗? (两个对象的底部、顶部、右侧和左侧)

标签: lua collision-detection love2d


【解决方案1】:

使用几个不同的测试输入在纸上检查并跟踪逻辑。你很快就会发现你的逻辑是荒谬的。你错过了一半的测试,你的一些比较是“指向错误的方式”等等。所以:

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

应该做的伎俩。

【讨论】:

  • 我也没有在任何对象移动时更新左侧、右侧等变量。现在都修好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多