Physics Engine for 2D Projects
-
Introduction
When creating 2D projects, you can use a physics engine to help you handle object movements and collision. You can think of a physics engine as an AI assistant to you. You just need to describe what you need from it, such as “make this ball fall with gravity”, then it will take care of the actual work. Using a physics engine will not only make your program more concise, but also make the result look more realistic.
Many great games are using a physics engine, such as “angry bird”, “pac-man”, or platformer games like “Super Mario”.
Initialize the 2D Physics World
To use the 2D physics engine, the very first step is to create a “physics world”. Unlike the stage or sprites, the physics world is an invisible world that works behind the scene. You will only know it is running by looking at the results it produces.
To initialize this world, you can use the following block in the “2D Physics” category:
This block takes 2 inputs, which are the gravity values in the X and Y directions.- For a platformer game like angry bird where you want the objects to fall to the bottom of the screen, you should set X gravity to 0 and Y gravity to a negative value like -100.
- For a top-down game like pac-man, you can set both gravity values to 0.
4 Walls Around the Physics World
After initializing the physics world, you will not observe any difference yet. However, 4 invisible walls will have been added on the 4 borders of the stage, so no object could move out of this area:
Note that if you have set the canvas dimensions to be greater than 480 by 360 for the viewport mode, these walls will be added around the enlarged canvas area. -
-