检查球与砖块的碰撞,并将砖块区域变成空白区域并反转 x 轴速度

为了制作我的项目,我希望当球撞击砖块并抹掉该特定砖块时,球可以反转速度,但是我无法利用我所拥有的知识工作。 编辑-找到了解决方案 https://github.com/itswaqas14/brickBreaker

block_pos  = {}  --  用于存储块位置的表
    rows, columns  = 30, 20  --  你决定有多少

    chance_of_block  = 75  --  放置块的%几率

    block_width  = math .floor( VIRTUAL_WIDTH /columns )
    block_height  = math .floor( VIRTUAL_HEIGHT /rows )

    col  = columns -1  --  不要遍历列,只使用最后一列

    for  row = 0,  rows -1  do

        if love .math .random() *100 <= chance_of_block then
            local xpos  = col *block_width
            local ypos  = row *block_height

            block_pos[ #block_pos +1 ] = { x = xpos,  y = ypos }
        end  --  rand

    end  --  #columns

并在 love.draw() 中打印生成的块

    for b = 1, #block_pos do
        local block  = block_pos[b]
        love .graphics .rectangle( 'line',  block.x + 5,  block.y,  5,  10 )
    end  --  #block_pos
    -- random 2nd line of blocks
    for b = 1, #block_pos do
        local block  = block_pos[b]
        love .graphics .rectangle( 'line',  block.x - 5,  block.y,  5,  10 )
    end  --  #block_pos

所有这些都在 main.lua 中,因为我不熟悉 Java 中的类概念,我在 ball.lua 中编写了一个基本的碰撞函数,该函数已导入 main.lua,并且我还编写了 paddle.lua 以控制挡板

    if self.x > box.x + box.width or self.x + self.width < box.x then
        return false
    end

    if self.y > box.y + box.height or self.y + self.height < box.y then
        return false
    end

    return true
end
点赞
用户3342050
用户3342050

那个球有多大?你需要将半径加入到你的碰撞检测中。你可以使用勾股定理 $a^2+b^2=c^2$ 如果你绝对需要对角线精度,但不用它会更快。在那个比例尺下,只有一两个像素,所以你甚至都不会注意到。

-- 球的右边 > 盒子的左边 or 球的左边 < 盒子的右边
if ( self.x +self.radius > box.x -box.width or self.x -self.radius < self.width +box.x )

-- 球的顶部 < 盒子的底部 or 球的底部 > 盒子的顶部
and ( self.y -self.radius < box.y +box.height or self.y +self.radius > self.height -box.y ) then

    block = nil  -- 碰撞检测成功,在该[index]位置上删除块
                 -- block_pos[b] = nil 根据你代码区域的措辞

    ball.dirX = -ball.dirX  -- 不确定你如何跟踪球的方向,但在这里让向量反射
end
2020-10-27 03:39:48