Game Development Reference
In-Depth Information
However, even after adding these two lines, the rectangle we created doesn't yet act as a physics
body, because we have not as yet marked it as a physics body. To do so, add the following line
of code:
physics.addBody( ground )
Upon refreshing the project in the simulator, the rectangle starts to obey gravity and falls down, off
the screen.
Let's create another object that falls; for simplicity's sake, we'll create another rectangle. To do this,
we'll alter the first line of the preceding code and place the ground object close to the bottom of the
screen rather than toward the top of the screen.
rect1 object
ground object.
Before we proceed, we need to know a few things. Creating a physics body is easy, but there are
a few different types of physics bodies that we can create, and their differences are important. A
physics body does not interact with other display objects; it can only interact with other physics
bodies. There are three main types of physics bodies: static, dynamic, and kinematic. The default
type of physics object is dynamic , which means that the moment we start the physics engine, this
object will start to obey the rules of gravity. The second type is static ; objects of this type stay in
place and do not obey gravity, but they still interact with physics objects. The last type is kinematic ,
in which the velocity affects the objects but gravity has no effect on it. A kinematic object moves
under the influence of its own velocity.
With this knowledge, we can write the following code:
local physics = require "physics"
physics.start()
local ground = display.newRect( 0, 460, 320, 20 )
local rect1 = display.newRect( 140, 0, 40, 40 )
physics.addBody( ground, "static")
physics.addBody( rect1 )
Now, as shown in Figure 8-12 , the rectangle for the ground does not fall off the screen, and the
rect1 rectangle bounces when it hits the ground.
Search WWH ::




Custom Search