3D Physics - Water Simulator (Difficulty: 2)
-
Introduction
In this tutorial, you will learn to use the 3D physics engine to control many water drops (spheres) for a fun animation. The 3D physics engine will manage the movement of 3D objects for us, which allows us to easily create complex 3D simulations with only a few blocks of code.
Step 1 - Initialize 3D Scene with Physics Engine
Please create a new project, remove the dog sprite, and add these blocks to initialize the 3D scene, 3D axis and the 3D physics engine.
Note that the gravity is set to -600, which makes objects move down (negative Z direction).
Step 2 - Add a static ground
We will start with a large, flat box to serve as the ground. To make sure it will not move or fall, we just need to set its mass to 0.
Step 3 - Add a bucket using as a rectangular cube
Next, let’s add a bucket to hold the balls. The “rectangular tube” shape is very convenient for this purpose. It is essentially a box, but you can change the cap type to “bottom”, so it is open on top.
Notes:- We need to move it up by 200 to be above the ground.
- You can apply any texture to it.
- We set its mass to be a large number like 10000, so it won’t be affected by the balls falling into it.
- Its restitution is 100%, so the balls will rebound when they hit the bottom or sides of this bucket.
Step 4 - Make the bucket spin
Since the bucket is controlled by the 3D physics engine, we can’t spin it using the “set speed” block. Instead, we need to use a special block in the “3D Physics” category to set the rotation speed around the Z axis:
Step 5 - Add a new sphere when SPACE key is pressed
To make the animation look cool, we will give each sphere a random color, which means their color/saturation/brightness are all random numbers. To keep the colors bright, we will set the range for brightness between 50 and 100.
Step 6 - Move the sphere to a random position
Next, we will move the new sphere to a random position, which means its x/y/z positions are all random.
Step 7 - Add a physics body
Lastly, we will hand over control of the ball to the 3D physics engine by attaching a “sphere” shape body to it. We will give it a very small mass so it won’t affect the movement of the bucket. Also, we will set it to 100% restitution, so it will bounce against other balls and the bucket.
Challenges
This project is very basic. You can challenge yourself with some of the following tasks:
- Add objects of different shapes and sizes
- Create a more complex container other than the bucket. For example, you can try to create a compound shape that is made of many boxes.
- Change the container to platforms: you can use many boxes to serve as platforms that are placed from top to bottom, so the balls will bounce from one platform to another like marbles.
-