Fixed Relative Position Constraint in 2D Physics
-
Introduction
When you are using the physics engine in your 2D project, you can add “constraints” to objects, and the physics engine will try to enforce these constraints.
One such constraint is “fixed relative position”, which tries to keep the relative position from one object to another the same. You can think of these 2 objects as one compound object when this constraint is in effect.
To add such a constraint, you can use the block below:
This block is very easy to use, since all that you need to specify is the other sprite. Both objects need to have been added to the physics world before this block is used.
Example 1 - At Least One Object is Fixed
When one of the 2 objects is “fixed”, then the other object will also be fixed at its position. Otherwise, the relative position between these 2 objects won’t stay the same.
In this example, there are 2 sprites “ball 1” and “ball 2”.
“ball 1” is fixed at the position of (0, 0):
“ball 2” is a dynamic object, but we are requesting that it keeps the same relative position to ball 1, so it would not fall due to gravity:
If you switch ball 2 to fixed and ball 1 to dynamic, the result is the same.
Here is the project link:https://play.creaticode.com/projects/807555715f43e2d84b9681ec
Example 2 - Both Objects are Dynamic
If both objects are “dynamic”, they may fall due to gravity, but their relative position stays the same.
In this project, we add a fixed box as well, and the 2 balls stay in the same relative position even when they collide with the box:
Here is the project link:https://play.creaticode.com/projects/c39685af2d5e5db422260ea0