Hi all,
I have 8 grenades grouped together in my game, when one explodes it pushes the other grenades using an applyLinearImpulse, which also sets of the other grenades around it, creating a chain reaction. Grenades remove themselves when the explosion happens.
This seems to work 9 out of 10 times. On the 10th time I get this error “attempt to call method ‘applyLinearImpulse’ (a nil value)”. I thought I would have handled this error by checking if the object still exists before applying the impulse, but no.
I think the problem is a very specific timing issue (I think).
Happening same cycle??
Grenade 1 - checks grenade 2 - returns OK
Grenade 2 - removes itself
Then (next cycle) Grenade 1 applies linear impulse on Grenade 2 - doesn’t exist anymore - error
Here is the offending code, I hope it enough for someone to give me an idea.
[lua]
pushCircle.collision = function (target, event)
if ( event.phase == “began”) then
if not event.other or event.other.removeSelf == nil then return end
local tempCor = math2d.sub(event.target, event.other)
local distance = math2d.length(tempCor.x, tempCor.y)
local angle = math2d.vector2Angle(tempCor.x, tempCor.y)
local vecX, vecY = math2d.angle2Vector( angle )
timer.performWithDelay( 1, function() – happening inside collision so add 1 millisecond delay
if not event.other or event.other.removeSelf == nil then return end
event.other.bodyType = “dynamic”
print(“event.other.id”, event.other.id)
event.other:applyLinearImpulse( -vecX * 100, -vecY * 100, event.other.x, event.other.y )
return true
end, “explosionTimer”)
end
end
pushCircle:addEventListener( “collision” )
[/lua]