what is the best way to spawn an endless amount of enemies with physics ? is it like this ?

Hi,

in my game, there’s enemies spawning until one can hit the player, I’m spawning the enemies like this:

[lua]

function spawnEne1()

    ene1 = display.newImageRect(group,“enemy1.png”, 42, 45)

    ene1.x = 560; ene1.y = math.random(screenTop+10, screenBottom)

    ene1.initY = ene1.y

    ene1.amp = math.random(20,90)

    ene1.angle = math.random(1,360)

    ene1.name = “ene”

    physics.addBody(ene1,“static”, {radius = 22})

    e1t = transition.to(ene1,{time = enespeed, x = player.x , y = player.y +40 , onComplete = function( obj ) 

        if(obj.removeSelf == nil) then return end

        if obj ~= nil then obj:removeSelf() end

    end})

    function moveEne1(self,e)

        self.angle = self.angle + .1

        self.y = self.amp*math.sin(self.angle)+self.initY

    end

    luck1 = math.random(1,3)

    if luck1 < 3  then

        ene1.enterFrame = moveEne1

        Runtime:addEventListener(“enterFrame”, ene1)

    end

    function ene1_collision(e)

        if e.other.name == “bullet” then

            spawnExplosionToTable(e.target.x,e.target.y)

        if e.target ~= nil then

        e.target:removeSelf()

    end

    end

    end

    ene1:addEventListener(“collision”, ene1_collision)

    return ene1

end

[/lua]

the monsters are going behind the player, I’m using three spawning functions like this because there’s more than one type of monsters, but obviously this is causing lag, so I’m wondering if there’s a better way of spawning for this kind of games that needs an endless spawning of enemies.

@hammod

Look into object pooling.  

I would determine how many enemies are on the screen at any time, and then create enough enemies when the game starts.  Store them in a table and reuse them when they collide or are killed, etc.  Add physics to these objects, and disable the enemies and physics routines during creation.  Pull from the pool when enemies are needed.

You may not even need to use different spawners… it might be possible to change the image and some of the object properties of the enemies during the pull from the pool.

The lag comes from the creation of new enemies and physics during game play.

@hammod

Look into object pooling.  

I would determine how many enemies are on the screen at any time, and then create enough enemies when the game starts.  Store them in a table and reuse them when they collide or are killed, etc.  Add physics to these objects, and disable the enemies and physics routines during creation.  Pull from the pool when enemies are needed.

You may not even need to use different spawners… it might be possible to change the image and some of the object properties of the enemies during the pull from the pool.

The lag comes from the creation of new enemies and physics during game play.