The code below is from a class that creates and returns an alien ship to main.lua in a space shooter game.
I need to include a function that determines what happens if this ship hits an object, but when I run the code, and the alien ship does hit something, I get the Corona Runtime Error:
attempt to call a nil value - start traceback: [C]:?
-- COLLISION FUNCTION
local function xenosColl(event)
if (event.phase == "began") then
print("hahf")
end
end
-- XENOS SHIP
function xenosShip.new()
local newXenosShip=display.newSprite( alShipSheet, alShipSeqData )
newXenosShip:play()
newXenosShip.x=580
newXenosShip.y=70
newXenosShipShape = {0,-40 , 60,0 , 0,40 , -60,0}
newXenosShip.myName = "newXenosShip"
physics.addBody(newXenosShip,"dynamic", {density = 1.0, friction = 0.3, bounce = 1, shape = newXenosShipShape})
newXenosShip:applyForce(0,2000,newXenosShip.x,newXenosShip.y)
newXenosShip:addEventListener("collision", xenosColl)
return setmetatable(newXenosShip, xenosShip_mt)
end
return xenosShip
If I remove the collision eventlistener, there is no error and the alien ship just bumps into the other object, so there must be something wrong with how it attempts to call the function, but I can't figure out what.
i create the same object just like you did and i get the error when i add the
return setmetatable(newXenosShip, xenosShip_mt)
i think it causes the object to become nil when you use setmetatable. try to remove the metatable