Time for action – adding the egg object

Imagine a world, full of falling eggs. It's not entirely too realistic, but in this game, we're creating this element. At least, we'll be making sure that both gravity and real-world physics will be applied. To add the egg object, perform the following steps:

  1. Create a new local function called eggDrop():
        local eggDrop = function()
  2. Add in the egg display object properties:
          local egg = display.newImageRect( "egg.png", 26, 30 )
          egg.x = 240 + mRand( 120 ); egg.y = -100
          egg.isHit = false
          physics.addBody( egg, "dynamic",{ density=eggDensity, bounce=0, friction=0.5, shape=eggShape } )
          egg.isFixedRotation = true
          gameGroup:insert( egg )
  3. Add in the postCollision event for the egg display object:
          egg.postCollision = onEggCollision
          egg:addEventListener( "postCollision", egg )
        end
    Time for action – adding the egg object

We have set the egg value for x with 240 + mRand( 120 ). The mRand function is equal to math.random, which will allow the egg to appear in randomized places in an area of 120 pixels, starting at 50 in the x direction.

It is vital to make sure that egg.isHit = false for the collision event to apply correctly. The physics body is set to "dynamic" so that it reacts to gravity and makes the object fall. There is a customized density and shape made for the egg we have created, which was already made at the beginning of the code.

The last important detail for the collision to work is adding egg to the onEggCollision() function with egg.postCollision = onEggCollision and then making the event listener use the "postCollision" event with egg:addEventListener( "postCollision", egg ).