You want to be assigning a value to each object you create to indicate what type of object it is, when it is created or spawned. I like to use
.class = 'ball'
for example.
So, I would create a ball in a spawning function like this:
function newBall(ballsGrp,x,y,radius) local ball = display.newCircle(ballsGrp,x,y,radius) ball.class = "ball" physics.addBody(ball,"dynamic",{radius=radius}) return ball end
The parameters are the parent display group of the balls (this should be different to the parent display group of the walls) and the location and size of the ball (which would be randomly generated by your code, I assume.)
So, you would create a wall in a similar way - I won’t provide that code because it is simply a rectangle with a static body type and .class=“wall”
Now, you could attach a collision listener to either the ball or the wall, but I would attach to the ball - personal preference, but the logic of the ball should be encapsulated within the ball constructor (the function which creates the ball) I believe.
When the collision occurs with an object with class “wall”, fire a timer (because you can’t remove physics object during a collision) and remove the ball. Here’s the complete newBall() function:
function newBall(ballsGrp,x,y,radius) local ball = display.newCircle(ballsGrp,x,y,radius) ball.class = "ball" physics.addBody(ball,"dynamic",{radius=radius}) -- function to handle the collision on the ball function ball:collision(e) -- only perform logic when the ball is colliding with a wall if (e.other.class == "wall") then -- cannot remove objects during a collision, so wait a short moment for it to end timer.performWithDelay(1, function() -- remove the ball ball:removeSelf() end, 1) end -- always return true because we have handled the collision return true end -- attach a collision listener to the ball ball:addEventListener("collision",ball) return ball end