1
votes

I'm using this code to spawn objectsbut sometimes i get this error ( Bad argument #-1 to 'addBody' (Proxy expected, got nil) ) any idea why?

local numberRock = 1

local function clearRock( thisRock )
   display.remove( thisRock ) ; thisRock = nil
end

local function spawnRocks()
    rockChek = math.random(1, 7)
    if  rockChek == 1 then
        rocks = display.newImageRect("rockes/rock1.png",110 ,86 )
    elseif  rockChek == 2 then
        rocks = display.newImageRect("rockes/rock2.png",97 ,65 )
    elseif  rockChek == 3 then
        rocks = display.newImageRect("rockes/rock3.png",101 ,61 )
    elseif  rockChek == 6 then
        rocks = display.newImageRect("rockes/rock4.png",95 ,59 )
    elseif  rockChek == 7 then
        rocks = display.newImageRect("rockes/rock5.png",107 ,77 )
    end   
    for i=1,numberRock do
        rocks.x = math.random(-10, 400);
        rocks.y =display.contentHeight + 100;
        transition.to( rocks, { time=2000,  y= display.contentHeight - display.contentHeight - 100 , onComplete=clearRock  } );
        physics.addBody( rocks, "dynamic", {density=.1, bounce=0.1, friction=.2, shape= shape2 ,filter=playerCollisionFilter } )   
        rocks.name = "rocks"
        rocks.isSensor = true
        rocks.rotation =  math.random(100, 1800)
   end
end
Rockspawner1 = timer.performWithDelay( 1500, spawnRocks, 0 )  
2

2 Answers

2
votes

You forgot to handle the cases where rockCheck is 4 or 5. Add those, and you will be fine.

Or, make the ramdom call go from 1 to 5 and replace 6 and 7 by 4 and 5 respectively.

By the way, really consider making rockCheck a local variable (with local rockCheck = ...)

1
votes

rocks is nil at the line below when the random value for rockCheck is 4 or 5

physics.addBody( rocks, "dynamic", {density=.1, bounce=0.1, friction=.2, shape= shape2 ,filter=playerCollisionFilter } )