Skip to content

Commit 813168b

Browse files
authored
Merge pull request #10943 from Calinou/physics-introduction-bitshift
Use bitshift and binary `OR` operator in to set layers in Physics introduction
2 parents 6ae63dd + 71d7086 commit 813168b

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

tutorials/physics/physics_introduction.rst

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,17 +170,25 @@ would be as follows:
170170
# Example: Setting mask value for enabling layers 1, 3 and 4
171171

172172
# Binary - set the bit corresponding to the layers you want to enable (1, 3, and 4) to 1, set all other bits to 0.
173-
# Note: Layer 32 is the first bit, layer 1 is the last. The mask for layers 4,3 and 1 is therefore
173+
# Note: Layer 32 is the first bit, layer 1 is the last. The mask for layers 4, 3 and 1 is therefore:
174174
0b00000000_00000000_00000000_00001101
175175
# (This can be shortened to 0b1101)
176176

177-
# Hexadecimal equivalent (1101 binary converted to hexadecimal)
177+
# Hexadecimal equivalent (1101 binary converted to hexadecimal).
178178
0x000d
179-
# (This value can be shortened to 0xd)
179+
# (This value can be shortened to 0xd.)
180180

181181
# Decimal - Add the results of 2 to the power of (layer to be enabled - 1).
182182
# (2^(1-1)) + (2^(3-1)) + (2^(4-1)) = 1 + 4 + 8 = 13
183-
pow(2, 1-1) + pow(2, 3-1) + pow(2, 4-1)
183+
#
184+
# We can use the `<<` operator to shift the bit to the left by the layer number we want to enable.
185+
# This is a faster way to multiply by powers of 2 than `pow()`.
186+
# Additionally, we use the `|` (binary OR) operator to combine the results of each layer.
187+
# This ensures we don't add the same layer multiple times, which would behave incorrectly.
188+
(1 << 1 - 1) | (1 << 3 - 1) | (1 << 4 - 1)
189+
190+
# The above can alternatively be written as:
191+
# pow(2, 1 - 1) + pow(2, 3 - 1) + pow(2, 4 - 1)
184192

185193
You can also set bits independently by calling ``set_collision_layer_value(layer_number, value)``
186194
or ``set_collision_mask_value(layer_number, value)`` on any given :ref:`CollisionObject2D <class_CollisionObject2D>` as follows:

0 commit comments

Comments
 (0)