The LitDev extension includes the LDPhysics object. This is an interface to the excellent Box2D engine originally written by Erin Catto. Box2D is an open source library that is used in professional games like Angry Birds and many others.
The Box2D engine allows shapes to realistically interact, bouncing off each other. Complex compound shapes like cars with moving wheels, inter-meshing cogs, objects connected with ropes and chains and many others can be created. LDPhysics integrates the Box2D physics engine with shapes and images within a Small Basic GraphicsWIndow. Not every feature of Box2D is included in LDPhysics, but it is quite extensive and most capabilities are catered for. The decision to do this means that there are a lot of methods in LDPhysics.
Despite the apparent complexity, the basic ideas are fairly simple and most methods are only their for advanced control of the engine.
- Create some shapes or images, set their positions.
- Add them to the physics engine ‘LDPhysics.Add…‘, setting their properties.
- Repeatedly call an update ‘LDPhysics.DoTimestep()‘ in an infinite game loop to do the physics interaction including move or rotate the shapes.
- User interaction is by applying forces to shapes; the engine itself updates their positions. Interactions are made before the update is made in the game loop.
In summary, the engine uses the laws of physics to update the positions of shapes as they interact with each other, leaving you free to concentrate on fancy visuals engaging game-play.
The documentation for Box2D is a good source for background understanding of the simulation engine. In addition, there is a detailed LDPhysics guide with plenty of examples included in the LitDev download. The following is an extract from this getting-started guide for the first and simplest example – just a ball that falls and bounces in a GraphicsWindow.
Example 1 – A falling ball
Create the objects in Small Basic
Attach to the physics engine
Give the ball friction=0 and restitution=1 (a bouncy ball).
Set its initial position near the top of the window with zero rotation (irrelevant for a circle) – if we don’t set its position in the engine it will take the current position of the shape.
Create a game loop
This is the repeating loop, where time-steps are performed to show the motion. The physics engine will update the position and rotation of the bodies and redraw them. We put a short delay to keep it smooth.
The whole thing
Below is a ‘pool game’ program that comes with the LitDev extension download.
Here is a screen shot from Zock77’s excellent dirt-bike game using LDPhysics.
In addition to developing your Small Basic games to a new level, it will improve your understanding of the physics describing the way forces, impulses and torques affect the movement of objects. Perhaps you may even want to try the Box2D engine in other languages; for example Java for Android games. The LitDev extension can be downloaded from http://litdev.hostoi.com.