Cannot gather worms

Hi you all, in my application, I used the following code to generate worms on a stone, and it works properly:

function addStone() Stone = display.newImageRect('Stone.jpg',150,150) Stone.anchorX = 0.5 Stone.anchorY = 1 Stone.x = display.contentWidth + 150 Stone.y = 700 Stone.type = "Stone" physics.addBody(Stone, "kinematic", {density=1, bounce=0, friction=0}) elements2:insert(Stone) worm[wormCtr] = display.newImageRect('worm.jpg',100,100) worm[wormCtr].anchorX = 0.5 worm[wormCtr].anchorY = 1 worm[wormCtr].x = display.contentWidth + 150 worm[wormCtr].y = 600 worm[wormCtr].type = "worm" physics.addBody(worm[wormCtr], "kinematic", {density=1, bounce=0, friction=0}) elements2:insert(worm[wormCtr]) wormCtr = wormCtr + 1 end 

then I added a collision event to let the character collect coins, but this one doesn’t work:

function onCollision(self,event) if ( event.phase == "began" ) then if(event.other.type == "platform" or event.other.type == "Column" or event.other.type == "Left") then timer.cancel(addColumnTimer) timer.cancel(moveColumnTimer) timer.cancel(addStoneTimer) timer.cancel(moveStoneTimer) elseif (event.other.type == "Stone") then for a = elements2.numChildren,1,-1 do if(elements2[a].x \> -100) then player:setLinearVelocity(elements2[a]:getLinearVelocity()) end end elseif (event.other.type == "worm") then worm[wormCtr]:removeSelf() worm[wormCtr] = nil end end end

Any suggestion? Thanks in advance! :) 

Hi @cabagnotmarc,

Collisions will not occur between two “kinematic” bodies. At least one body involved in a collision must be “dynamic” (or both can be).

Best regards,

Brent

the character colliding on the worm is “dynamic”. and there is an error that when the character collides on a worm it says that the worm is a nil value.

OK, I see now. This is an issue in your collision handling function then. Have you fully read through the guide on collision detection, and the different options (“local” vs. “global”) for collision handling? There are ways to reference/get the object(s) involved in collisions without directly pointing to the variable(s) in which you declared them.

https://docs.coronalabs.com/guide/physics/collisionDetection/index.html

Brent

Hi @cabagnotmarc,

Collisions will not occur between two “kinematic” bodies. At least one body involved in a collision must be “dynamic” (or both can be).

Best regards,

Brent

the character colliding on the worm is “dynamic”. and there is an error that when the character collides on a worm it says that the worm is a nil value.

OK, I see now. This is an issue in your collision handling function then. Have you fully read through the guide on collision detection, and the different options (“local” vs. “global”) for collision handling? There are ways to reference/get the object(s) involved in collisions without directly pointing to the variable(s) in which you declared them.

https://docs.coronalabs.com/guide/physics/collisionDetection/index.html

Brent