Great! That’s what checkCollisions does. It gives a list of the collisions that occur for any given x and y without moving the sprite. You've given it the x and y of the brick, so it returns a collision with the brick. And then you've asked it to remove brick if it detects a collision. So it’s working!
What you probably want to do is ball:moveWithCollisions each frame. That way, the ball will move, but only return a collision if it actually collides.
So however you were moving the ball before, replace that with something like:
actualX, actualY, collisions, length = ball:moveWithCollisions(newX, newY)
Then paste in the bit that removes the bricks that ball collides with:
for i = 1, length do
collisions[i].other:remove()
print("removed brick")
-- and when you have a score variable:
-- score += 1
end
... and then it still won't work the way you want, because now it'll destroy any sprite it contacts, which might include walls and your paddle!
There are a number of ways to deal with this. Your code above only has one brick, called brick, so you could do:
for i = 1, length do
if collisions[i].other = brick then
collisions[i].other:remove()
print("removed brick")
-- and when you have a score variable:
-- score += 1
end
end
But that's going to get tricky when you have dozens of bricks. I tend to just give all my sprites a type. I'd add self.type = "brick"
to brick:init
and self.type = "paddle"
to paddle:init
and self.type = "ball"
to ball.init
. More experienced people probably have better ways.
But then you can do:
for i = 1, length do
if collisions[i].other.type = "brick" then
collisions[i].other:remove()
print("removed brick")
-- and when you have a score variable:
-- score += 1
end
end
Apologies in advance for any errors!