Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

7. Physics: Falling Objects > Time for action – adding the egg object

Time for action – adding the egg object

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 the gravity and real-world physics will be applied. Create a new local function called eggDrop(). local eggDrop = function() 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 ) Add in the postCollision event for the egg display object. egg.postCollision = onEggCollision egg:addEventListener( "postCollision", egg ) end What just happened? We have set the egg value for x to 240 + mRand( 120 ). The mRand function equals 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 egg.isHit = false for the collision event to apply correctly. The physics body is set to "dynamic" so it reacts to gravity and makes the object fall. There is a customized density and shape made for the egg that we created, which is 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 ).

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint