How do I make an efficient Update function?

Hi everyone!

I’m just about to start working on an update function for my game but I wanted to ask if you guys know a better way performance wise.

I’m planning to make an “enterFrame” runtime listener that calls a function called update() this will in turn call the individual update functions for each of my entities that requires this.

So something like this
[lua]function update(event)
npc:update()
walls:update()
– etc.
end

Runtime:addEventListener(“enterFrame”, update) [/lua]

Also, I really don’t want all of my update functions to be called on every frame, how do I limit the calls to be every x frame? [import]uid: 129450 topic_id: 23240 reply_id: 323240[/import]

You can have a variable that keeps a frame count, so then based on it you call your functions. In this example npc:update() will be called every 2 frames, and walls:update() every 3 frames.

In case you don’t know what the % operator does. It returns the remainder of an integer division. So for example, for frameCount%2 it will return 0 when frameCount is a multiple of 2, and 1 otherwise (another way to look at it, 0 when even, 1 when odd).

[code]
local frameCount = 0

function update(event)
if(frameCount%2 == 0) then
npc:update()
end

if(frameCount%3 == 0) then
walls:update()
end

frameCount = frameCount + 1
end

Runtime:addEventListener(“enterFrame”, update)
[/code] [import]uid: 61899 topic_id: 23240 reply_id: 93053[/import]

In my framework it’s something like this – pseudo code follows:

function appMainLoop()  
 doStuff()  
  
 for each sprite in app.sprites (my big sprites array)  
 if sprite.handle ~= nil then sprite:handle() end  
  
 do miscellaneous other sprite stuff (removing, moving,  
 fading, etc. based on properties like x, y, energy, speedX...)  
 end  
end  

And then for a specific sprite it would look something like this:

function self:createSpriteAlien()  
 local function self(handle)  
 -- do sprite type specific stuff here  
 end  
  
 local sprite = createSprite(type, position, size, doesUsePhysics, etc.)  
 sprite.energySpeed = -1  
 sprite.alphaChangesWithEnergy = true  
 sprite.speedX = 2  
 sprite.disappearsWithParent = true  
 etc.  
 addSprite(sprite, handle, moduleGroup, handleWhenGone)  
end  

Every sprite is an object of a sprite class, which contains the default Corona body properties but also much more properties and functionality. Good luck! [import]uid: 10284 topic_id: 23240 reply_id: 93056[/import]

Thanks for the help Clueless and Philipp, just what I was looking for! [import]uid: 129450 topic_id: 23240 reply_id: 93260[/import]

By the way Clueless, wouldn’t your solution mean that the framecount would get extremely high after playing for a while and because of that cause the calculation to slowdown the game? [import]uid: 129450 topic_id: 23240 reply_id: 93274[/import]