display.remove() in Collision function doesn't work, please help!

(Sorry for creating new topic in the wrong field “Other”)

Hi, I am a newbie from Hong Kong. Here is the problem.

The object’s code:

[lua]function addInitialBlocks()
blocks = display.newGroup()
for i = 1, 1 do
block = display.newImageRect(“assets/brickblock.png”, 114, 15)
block.x = math.random() * (display.contentWidth - (block.width * 0.5))
block.y = (display.contentHeight * 0.5) + (math.floor(math.random() * (display.contentHeight * 0.5)))
block.name = “block”
physics.addBody(block, {density = 1, bounce = 0})
block.bodyType = “static”
blocks:insert(block)
end
end[/lua]

[lua]function addBlock()
block = display.newImageRect(“assets/brickblock.png”, 114, 15)
block.x = math.random() * (display.contentWidth - (block.width * 0.5))
block.y = display.contentHeight + block.contentHeight
block.name = “block”
physics.addBody(block, {density = 1, bounce = 0})
block.bodyType = “static”
blocks:insert(block)
end[/lua]

In these two codes, I named all the blocks created as “block”. Then I created a function of collision:

[lua]function protesterCollision(event)
if (event.phase == “began” and event.other.name == “block”) then
protesterhp = protesterhp - 1
protesterhpText.text = "Protester HP: " … protesterhp
end

end[/lua]

Protester is the player, the function of collision I created works, the HP of protester is deducted once the collision is detected.

However, the other function of collision doesn’t work:

[lua]function popogunCollision(event)
if (event.phase == “began” and event.other.name == “block”) then
display.remove(event.other)
end
end
[/lua]

These two codes basically are 100% logically the same, in fact, in the popogunCollision(event), there are more other objects, which I designed to be removed once the collision occurs. In the popogunCollision(event), all other objects’ collision work fine, except the one with “block”.

Would anyone please help check what I have missed or done wrongly?

Thank you!

You seem to be mixing local and global collision listeners.

Have a look at https://docs.coronalabs.com/api/event/collision/index.html#object-references.

Essentially, in both of your collision listeners, you only have  event as a parameter, which would suggest that you are using a global collision listener. However, inside the function you are checking the value of  event.other.name , but event.other belongs to a local collision listener and so you won’t find it inside a global one.

So, just pick one or the other and you should get it working.

The difference between the two are explained quite clearly in here: https://docs.coronalabs.com/guide/physics/collisionDetection/index.html#collision-handling

XeduR @Spyric,

thank you for your advice. I solved this problem before this post was approved.

Found that collision function doesn’t work when both objects are static objects.

Anyway, thank you very much!