I'm pretty new to LÖVE (and gamedev in general), and have been trying to make a Breakout/Brick Breaker style game, but I've run into some problems with making the ball bounce off the blocks. My current code works for the most part, but I assume there's a much more efficient/idiomatic way to handle this, and currently when the ball hits two blocks at once it just goes right through them, which isn't exactly what I intended. If anyone has any tips it would be greatly appreciated.
Here's the collision handling code in my 'play' gamestate:
Code: Select all
local loop = true
for x = 0, blocks.columns - 1 do -- Iterate through block array columns
for y = 0, blocks.rows - 1 do -- Iterate through block array rows
local currentBlock = blocks.array[x][y]
-- Blocks deactivate and reflect ball when they get hit
if ball:collides(currentBlock) and currentBlock.active then
currentBlock.active = false
blockCount = blockCount - 1
if ball:xAxisCollides(currentBlock) then
ball.dy = -ball.dy
loop = false
break
else
ball.dx = -ball.dx
loop = false
end
end
if not loop then break end
end
end
Code: Select all
function Ball:collides(object)
if self.x > object.x + object.width or object.x > self.x + self.width then
return false
elseif self.y > object.y + object.height or object.y > self.y + self.height then
return false
else
return true
end
end
function Ball:xAxisCollides(object)
local ballCenter = {self.x + self.width / 2, self.y + self.height / 2}
local objectCenter = {object.x + object.width / 2, object.y + object.height / 2}
local distanceX = math.sqrt((ballCenter[1] - objectCenter[1]) ^ 2) / object.width
local distanceY = math.sqrt((ballCenter[2] - objectCenter[2]) ^ 2) / object.height
if distanceY > distanceX then
return true
else
return false
end
end