检查球与砖块的碰撞并将砖块区域撤消为空白 space 并反转 x 速度

Check collision of ball with brick and undo the brick area to blank space and reverse the x velocity

为了制作我的项目,我希望球在被砖块击中时反转速度并擦除该特定砖块,但无法利用我所掌握的知识进行工作。 编辑 - 找到解决方案 https://github.com/itswaqas14/brickBreaker

block_pos  = {}  --  table to store block positions
    rows, columns  = 30, 20  --  you decide how many

    chance_of_block  = 75  --  % chance of placing a block

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

    col  = columns -1  --  don't loop through columns, just use final column

    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 中的 Class 概念并且我在 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

那个球有多大?您需要将半径添加到碰撞检测中。如果您绝对需要对角线精度,则可以使用 pythag a² +b² = c² ,但没有它会更快。在那个比例下,它只有一两个像素,所以你甚至不会注意到。

--  right side of ball  >  left side of box  or  left side of ball  <  right side of box
if ( self.x +self.radius > box.x -box.width or self.x -self.radius < self.width +box.x )

--           top of ball  <  bottom of box    or     bottom of ball  >  top of box
and ( self.y -self.radius < box.y +box.height or self.y +self.radius > self.height -box.y ) then

    block = nil  --  collision detected, get rid of block at that [index] location   
                 --  block_pos[b] = nil    however you have it worded in this region of code

    ball.dirX = -ball.dirX  --  not sure how you are keeping track of ball direction,
                            --  but make vector reflect here
end