I am trying to make a particle physics side scroller game but I’ve run into an annoying bug. When the particle collides into a wall or another particle while a force is being applied to it, I get an error saying “game.lua:115: attempt to call method ‘applyForce’ (a nil value)”. This error does not appear when the particle collides with something without force being applied.
Here is the code that I believe is causing the problems:
[lua]
particle = display.newImage(“particle.png”)
particle.y = display.contentHeight / 2
particle.x = display.contentWidth / 4 - 20
particle.collided = false
physics.addBody(particle, “dynamic”, {density=0.1, bounce=0.1, friction=0.2, radius=12})
screenGroup:insert(particle)
function activateParticle(self, event)
self:applyForce(0, -2.5, particle.x, particle.y)
end
function touchScreen(event)
if event.phase == “began” then
particle.enterFrame = activateParticle
Runtime:addEventListener(“enterFrame”, particle)
end
if event.phase == “ended” then
Runtime:removeEventListener(“enterFrame”, particle)
end
end
function gameOver()
storyboard.purgeScene(“game”)
storyboard.gotoScene(“game”)
end
function onCollision(event)
if event.phase == “began” then
if particle.collided == false then
particle.collided = true
particle.bodyType = “static”
timer.performWithDelay(3000, gameOver(), 1)
end
end
end
function scene:enterScene(event)
storyboard.purgeScene(“start”)
storyboard.purgeScene(“restart”)
Runtime:addEventListener(“touch”, touchScreen)
background.enterFrame = scrollBackground
Runtime:addEventListener(“enterFrame”, background)
background2.enterFrame = scrollBackground
Runtime:addEventListener(“enterFrame”, background2)
particle1.enterFrame = moveParticles
Runtime:addEventListener(“enterFrame”, particle1)
particle2.enterFrame = moveParticles
Runtime:addEventListener(“enterFrame”, particle2)
particle3.enterFrame = moveParticles
Runtime:addEventListener(“enterFrame”, particle3)
Runtime:addEventListener(“collision”, onCollision)
print(“created all”)
end
function scene:exitScene(event)
Runtime:removeEventListener(“touch”, touchScreen)
Runtime:removeEventListener(“enterFrame”, background)
Runtime:removeEventListener(“enterFrame”, background2)
Runtime:removeEventListener(“enterFrame”, particle1)
Runtime:removeEventListener(“enterFrame”, particle2)
Runtime:removeEventListener(“enterFrame”, particle3)
Runtime:removeEventListener(“collision”, onCollision)
print(“removed all”)
end
function scene:destroyScene(event)
end
scene:addEventListener(“createScene”, scene)
scene:addEventListener(“enterScene”, scene)
scene:addEventListener(“exitScene”, scene)
scene:addEventListener(“destroyScene”, scene)
return scene
[/lua]