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

  • 本文关键字:区域 空白 速度 碰撞 撤消 lua love2d
  • 更新时间 :
  • 英文 :


在制作我的项目时,我希望球在与砖块碰撞时反转速度,并擦除特定的砖块,但无法使用我所掌握的知识。EDIT-找到解决方案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.lia中导入,我还编写了用于控制桨板的桨板.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

最新更新