Game Development Reference
In-Depth Information
If we run this code at this point, it will do nothing. We still need to draw the body onto the screen. To
do so, in the love.draw() function, we draw the shapes:
function love.draw()
love.graphics.rectangle("fill", body:getX(), body:getY(), 20, 40)
end
You will now see the rectangle drawn at the top-left corner of the screen. It does not automatically
move like a physics body should. This is because the mass is currently set to 0, which means that the
body does not move, as it is weightless. If we change that and assign it a little weight, it will start to
descend or ascend (depending on the gravity settings). If we give the object a positive weight value in
this example, it will off the screen, as there is no other object to stop it from falling off the screen.
bodyShape is that since this
body:getX()
body:getY() functions, we get the current x and y position of the object and draw it there. If we
love.load() function:
ground which is a rectangular-shaped body and then we add this
love.draw() function, which will render the shape solid:
love.graphics.polygon("fill", groundShape:getPoints())
Now we have a ground at the bottom that will prevent the smaller physics body from falling off
the screen.
We can also add interactivity by adding an impulse to the object when the mouse is clicked. We do
this via the love.mousepressed function.
function love.mousepressed(key, button)
if button == "l" then
body:addImpulse(0,-20)
end
end
When we click in the window, the object jumps up and then lands on the ground again. You can
change the impulse value to a larger or smaller number to vary the results.
When the object goes out of the world that we set, it gets removed, so if it jumps up too high, it will
not return. If you want the object to jump off the screen and return, then you'll need to create a world
that is larger than the screen size—for example:
world = love.physics.newWorld(−_W, -_H, _W*2, _H*2)
Search WWH ::




Custom Search