In the previous chapter, we talked about how to integrate the physics engine into your code. We also started implementing physical bodies to the brick objects, and now, we'll need to do the same with other active game objects, such as the paddle and ball. Let's continue with this last half of the tutorial. We will continue using our main.lua
file from the Breakout
project folder.
Corona display objects can be turned into simulated physical objects using one line of code. The following information explains the different forms of physics bodies:
A body shape is a table of local (x,y) coordinates relative to the center of the display object.
The syntaxes for the body shapes are as follows:
physics.addBody(object, [bodyType,] {density=d, friction=f, bounce=b [,radius=r]})
physics.addBody(object, [bodyType,] {density=d, friction=f, bounce=b [,shape=s]})
The following are the examples of the body shapes:
local ball = display.newImage("ball.png") physics.addBody( ball, "dynamic" { density = 1.0, friction = 0.3, bounce = 0.2, radius = 25 } )
local rectangle = display.newImage("rectangle.png") rectangleShape = { -6,-48, 6,-48, 6,48, -6,48 } physics.addBody( rectangle, { density=2.0, friction=0.5, bounce=0.2, shape=rectangleShape } )
Now, we will discuss the parameters of the preceding methods:
Object
: This is a display object.bodyType
: This is a string that specifies that the body type is optional. It uses a string parameter before the first body element. The possible types are "static"
, "dynamic"
, and "kinematic"
. The default type is "dynamic"
if no value is specified. Let's talk about these types:Density
: This is a number that is multiplied by the area of the body's shape to determine mass. It is based on a standard value of 1.0 for water. Lighter materials (such as wood) have a density below 1.0, and heavier materials (such as stone) have a density greater than 1.0. The default value is 1.0
.Friction
: This is a number. This may be any non-negative value; a value of 0 means no friction, and 1.0 means fairly strong friction. The default value is 0.3
.Bounce
: This is a number that determines the object's velocity that is returned after a collision. The default value is 0.2
.Radius
: This is a number. This is the radius of the bounding circle in pixels.Shape
: This is a number. It is the shape value in the form of a table of the shape vertices, that is, {x1, y1, x2, y2, …, xn, yn}, for example, rectangleShape = { -6,-48, 6,-48, 6,48, -6,48 }
. The coordinates must be defined in a clockwise order, and the resulting shape must be convex only. Physics assumes that the (0,0) point of an object is the center of the object. A -x coordinate will be to the left of object's center and -y coordinate will be at the top of object's center.