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

问题描述

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

interface

并在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()

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

    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.x - 5,10 )
    end  --  #block_pos

解决方法

那个球有多大?您需要将半径添加到碰撞检测中。如果您绝对需要对角线精度,则可以使用pythaga²+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