Rigid Bodies
This lesson will introduce you to the basics of the physics engine. It is a great tool for simulating realistic 2D physics in your game. Let's set up our engine by calling the Physics class.
First we create our variable engine, then we call engine.update() in the game loop. This calculates each frame for the physics simulation. Now let's create a box and rotate it by 10°.
We can add it to the physics environment by giving it a body.
Now our box falls from the sky! We can give it something to land on by creating another rectangle for the ground.
But our box falls through the ground! This is because we haven't given the ground a rigid body. We don't want the ground to be affected by gravity, so we use the STATIC variable to keep it in the same place.
Now our box falls and hits the ground. How can we make it more interesting? We could try changing the elasticity (bounciness) of the box.
In the code above, we also change the ground's elasticity to make the bounce more effective. An elasticity of 0 prevents the object from bouncing, and an elasticity of 1 makes the object bounce forever.
Now you know the basics of simulating 2D physics! You could even try changing the direction of gravity, but you'll need to add a ceiling for the box that falls upwards.
Our basic physics demo uses the concepts in this tutorial to create a particle simulation.
Back Next