Skip to content

Commit 71d7086

Browse files
committed
Use bitshift and binary OR operator in to set layers in Physics introduction
1 parent f86a5dc commit 71d7086

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
@@ -168,17 +168,25 @@ would be as follows::
168168
# Example: Setting mask value for enabling layers 1, 3 and 4
169169

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

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

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

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

0 commit comments

Comments
 (0)