如何在Love2d中使用包围盒?

目前我使用了非常笨重的代码来检测简单对象之间的碰撞。我听说过包围盒,但是找不到任何关于如何使用它的教程,所以我想问一下如何使用它。以下是我目前检测碰撞的方式:

    function platform.collision()
if player.x + player.width / 2 <= platform.x + platform.width and
    player.x + player.width / 2 >= platform.x and
    player.y + player.height <= platform.y + platform.height and
    player.y + player.height >= platform.y then
点赞
用户2505965
用户2505965

MDN 上有一篇简洁的关于2D 碰撞检测的文章。作为 MDN,示例是用 javascript 写的,但很容易翻译成任何语言,包括 Lua。

让我们来看看:

坐标轴对齐边框盒子

最简单的碰撞检测之一是在没有旋转的两个矩形之间进行轴对齐 —— 意思是没有旋转。该算法通过确保矩形的四个边缘之间没有间隙来工作。任何间隙都意味着不存在碰撞。

他们的示例被翻译成了 Lua:

local rect1 = { x = 5, y = 5, width = 50, height = 50 }
local rect2 = { x = 20, y = 10, width = 10, height = 10 }

if
    rect1.x < rect2.x + rect2.width and
    rect1.x + rect1.width > rect2.x and
    rect1.y < rect2.y + rect2.height and
    rect1.height + rect1.y > rect2.y
then
    -- 碰撞检测到!
end

-- 填充值 =>

if
    5 < 30 and
    55 > 20 and
    5 < 20 and
    55 > 10
then
    -- 碰撞检测到!
end

一个 JavaScript 实时示例 很好地展示了这一点。


这里有一个可以放入 main.lua 中并进行调试的快速(但不完美)的 Love2D 示例。

local function rect (x, y, w, h, color)
    return { x = x, y = y, width = w, height = h, color = color }
end

local function draw_rect (rect)
    love.graphics.setColor(unpack(rect.color))

    love.graphics.rectangle('fill', rect.x, rect.y,
        rect.width, rect.height)
end

local function collides (one, two)
    return (
        one.x < two.x + two.width and
        one.x + one.width > two.x and
        one.y < two.y + two.height and
        one.y + one.height > two.y
    )
end

local kp = love.keyboard.isDown
local red = { 255, 0, 0, 255 }
local green = { 0, 255, 0, 255 }
local blue = { 0, 0, 255, 255 }

local dim1 = rect(5, 5, 50, 50, red)
local dim2 = rect(20, 10, 60, 40, green)

function love.update ()
    if kp('up') then
        dim2.y = dim2.y - 1
    end

    if kp('down') then
        dim2.y = dim2.y + 1
    end

    if kp('left') then
        dim2.x = dim2.x - 1
    end

    if kp('right') then
        dim2.x = dim2.x + 1
    end

    dim2.color = collides(dim1, dim2) and green or blue
end

function love.draw ()
    draw_rect(dim1)
    draw_rect(dim2)
end
2016-11-11 06:51:00