Distance Constraint between 2 Physics Objects
-
Introduction
When you have enabled the physics engine in a scene, you can add constraints between objects. A constraint is a request that we give to the physics engine, and the physics engine will try its best to satisfy our request.
For example, a distance constraint is a request that we wish to force the distance between 2 objects to stay the same no matter how they move.
Note that the physics engine may not always be able to satisfy our constraint requests, so you need to test our program to make sure your constraint requests are realistic.
The “Add Distance Constraint” Block
To add a distance constraint, you can use the following block:
The first 2 inputs allow you to specify the first object from any sprite, and the next 2 inputs allow you to specify a second object from any sprite. Note that if one of these 2 objects is static (mass = 0), then you should specify that object’s name and sprite in the first 2 inputs.The last input is optional: it is the name of the constraint you are creating. If you need to remove this constraint later, then you need to refer to this constraint using its name.
After this block runs, the physics engine will try its best to keep these 2 objects at the same distance as before this block runs. These objects can still move, but their distance will stay the same.
Example
In this program, we add 2 spheres A and B. Sphere A does not move, while sphere B can move freely. Sphere B is added at a distance of 200 to the right of sphere A, so after we add the distance constraint, their distance will remain at 200, but sphere B will be swinging around A due to gravity.
Here is how it looks:
The “Remove Constraint” Block
You can remove a constraint at any time using the following block:
Note that this block requires you to input the name of the constraint to be removed.
Demo
Suppose we are running the example program above. If we click the “remove constraint” block while sphere B is swinging, then sphere B will start to fall freely: