Set Rotation Axis 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 “set as rotation axis”, which sets another sprite as the rotation axis of the current sprite. The current sprite can not move further away or closer, but can rotate around the axis object.
To set another sprite as the rotation axis, you can use the block below:
This block accepts 3 input parameters. The first input is the target sprite to be used as the rotation axis.The next 2 inputs allow us to set the position offset in the X and Y directions. When these 2 inputs are both 0, the rotation axis will be located at the same position as the target sprite. For example, if the target sprite is at x of 100 and y of 30, then the rotation axis will also be at x of 100 and y of 30.
However, we can change the location of the axis by adding offsets in the X and Y directions. For example, if the x offset is 20, then the rotation axis will be at x of 100 + 20 = 120.
Example 1 - The Target Object is Fixed
The most common way of using the “set rotation axis” block is to have a fixed target object as the rotation axis, so the current sprite would rotate around that object.
In this example project, there are 2 sprites: “blue ball” and “yellow ball”.
“blue ball” is fixed at the position of (0, 0):
“yellow ball” is a dynamic object, but we only allow it to rotate around the blue ball, so when it falls due to gravity, it starts to rotate around the blue ball.
Here is the result:Here is the project link:
https://play.creaticode.com/projects/05790f959a134a91cea4adb1
Example 2 - Both Objects are Dynamic
If both objects are “dynamic”, they may fall due to gravity, but their relative distance remains the same.
In this project, we add a fixed box as well, and the 2 balls stay at the same distance even when they collide with the box.
Here is the project link:https://play.creaticode.com/projects/d8edf376adf1569625ca69ef
Remove the Rotation Axis
To remove the rotation axis, you can use the following block:
Set Rotation Speed for the Rotation Axis
After setting a rotation axis, you can also set a rotation speed for that axis, which will make the current sprite rotate at that speed. This is handy if you want to simulate a wheel.
You can use the following block to set the rotation speed:
The speed input is a degree number. For example, if it is 180 degrees, the axis will rotate for 180 degrees every second.The second input is a damping factor between 0 and 100, which controls how fast the rotation speed slows down over time. At 0%, it will not slow down at all.