Ok, I’m going to admit, this part is brutally pasted on to the rest of this tutorial… it really serves no purpose for the “game” we’ve created so far, but hey… physics engines are cool, Defold has a physics engine, might as well show how it works, no? So, time to add some debris from the heavens to our game!
A physics engine is a math-based simulation that runs in your game engine and calculates how objects in the simulation affect each other, then updates the attached game objects position accordingly. There are a number of different ways to interact with physics simulation. A rigid body is a full on simulated object, if something hits it, it moves, if it hits something else in the simulation, they both respond. Next up you have kinematic objects. These are objects that interact with the simulation, but are generally moved much more directly… normally this is the player. Think of the physics simulation and all those rigid bodies as the china shop, and the kinematic character… that’s the bull. It’s also possible to set up triggers, these just watch for collisions, but don’t interact with other objects in the simulation. Generally, you use a trigger to detect and respond to a collision, whether it triggers (hey… good name!) some code or not. Don’t worry, it sounds much more complex than it is!
In main.collection, let’s start off by creating a floor for our physics simulation to run on. Add a Game Object to main called physics floor. Now right-click, Add Component and choose Collision Object.
Now under type select Static.
A static object is in the simulation but isn’t affected by it. Throw as much weight against a static object as hard as you want… nothing will happen… to the static object. Now the thing that hit the static object… that’s another story!
Finally, we need to create a shape to define our presence in the simulation. Right-click the collision object, select Add Shape, then Box.
Now set the dimensions of the box to cover the bottom of the screen, then move it to the bottom.
Now create another game object, this one named physicsObject. Add a sprite to it, pick any from our atlases, it doesn’t really matter. Then add a collision object as well and create a shape that roughly matches the sprite. The end result should look like:
Now use the following settings for the collision object:
A dynamic object (also known as a Rigid Body in other engines) is fully manipulated by the physics engine. Gravity will immediately grab ahold of it and it will come crashing down until it hits the ground. Oh, speaking of gravity…. If you head back to game.project, you can find several physics settings, like so: