Game Development Reference
In-Depth Information
body2 = world:addBody(MOAIBox2DBody.STATIC)
fixture2 = body2:addRect(-5,-5,5,-3)
fixture2:setFilter(0x02)
fixture2:setCollisionHandler(onCollide, MOAIBox2DArbiter.BEGIN + MOAIBox2DArbiter.END, 0x01)
This creates a static body, which acts as a ground that prevents the dynamic box from falling off the
screen.
For both the body fixtures, we also set a collision handler that calls the function
onCollide
for the
events
MOAIBox2DArbiter.BEGIN
and
MOAIBox2DArbiter.END
. The
BEGIN
event is triggered when
a collision starts to occur and the
END
event is triggered when it ends. We can capture it in the
onCollide
function.
if event == MOAIBox2DArbiter.BEGIN then
print("Begin!")
elseif event == MOAIBox2DArbiter.END then
print("End!")
end
texture:setRect(-0.5, -0.5, 0.5, 0.5)
Now we need to add this image to the body:
image = MOAIProp2D.new()
image:setDeck(texture)
image:setParent(body)
layer:insertProp(image)
The polygon that we created using
poly
is diamond shaped; if we want it to be a square, we can use
the following:
poly = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5}
The object does not bounce when it comes in contact with the ground. We can make both objects
bouncy by setting the restitution, using the
setRestitution
function.
fixture:setRestitution(0.5)
and
fixture:setRestitution(0.7)
To make this little code sample more fun, let's change the gravity of the world to −1, which will make
the object act like a balloon. To do this, we use
world:setGravity(0,-1)
. The object now falls down
slower. We can also add a mouse event that will make the object bounce.