Step 6: Main Loop

Setting up a Main Loop

You may have noticed that the penguins fly off into the distance after a while.
To prevent this we’ll use a main loop to keep them close to the center of the world.
If you use a Timer.every you can schedule a function to be run every frame, or every so often.
The first argument to Timer.every is the function you want to run, the second is the number of seconds between executions.
A duration of 0 is special cased to run once every frame.


In your main loop function you can get a list of SceneObjects that contain the keyword “target”.
Using a for loop to loop through this list you can apply a force to each that will push them slightly back towards the center.
Since this runs every frame, the penguins will have a tendency to be pulled back to the middle of the pocket.


Congrats!  You have built a basic pocket that creates objects, captures users
input, moves the camera, handles collisions and uses a main loop.


    -- onSceneStart is called first to start the game
function onSceneStart()
-- Output to the debug console
print ("Hello World")
        -- Add camera controls
        -- Set initial camera position
        -- Add an event map to handle firing projectiles
    map =
        -- Create six targets
    for i=1,6 do
        -- Start the function that will draw the targets to the center
function attractTargets()
    -- Loop through every target
    for k,v in pairs(SceneManager.getByKeyword("target")) do
        -- Apply a force directly opposite of the targets position
        v:applyForce(v:getPosition() * -10)