All Questions

Community

Luca Leonardi(LuxeL)
posted to: Project Setup

Flags that can hold more than two values

Why does Godot uses bit values for layers? You wrote "We use the bit-wise left-shift operator (<<) because Godot stores layers as bit values. [...] This is a common way to handle flags that can hold more than two values.". But can't layers be ONLY two values? True or False?
  • GDQuestions replied

    Yes, you can set individual layer bits on or off from GDScript, but "true" and "false" are respectively a 1 and a 0 for the computer.

    Typically, anything that works like a series of switches (options you can turn on or off) is a series of 0 and 1 for the computer.

    In the case of layers, you have a couple dozens of them, so a couple dozens of 0 and 1s chained together.

    The combination of layers active or not is a series of 0 and 1s, so you can treat it as a number too - you can represent it in binary form (for example, 0b0000000000...). 

    You can also represent it in base 10: you can very well set the whole layers at once using a number like 7 and it'll turn on multiple layers at once. Why? Because 7 == 2^0 + 2^1 + 2^2 == 0b0111 in binary form. The latter part is what the computer sees.

    As you can see, there are multiple ways you can think of this. Using binary numbers can be uncommon in scripting languages, but it's still useful and can lead to huge performance boosts in some algorithms, so they're good to know.

  • Luca Leonardi(LuxeL) replied

    Thank you!

    It still not being very clear why you should want to turn 3 layers on at the same time with, for example, the value 7 (= 0b111), and moreover HOW you would achieve something like that... In GDScript we have "set_collision_layer_bit()" that accepts two values: the bit, which is an int, that determines the layer that we're refering to, and the value, which is a boolean, and sets the layer on or off. How could I set the whole layers at once?

  • GDQuestions replied

    You can directly assign a value to the collision_layer property to set multiple layers at a time. I mostly meant to show how 0b0111 is a number, it's just the base 2 (binary) form of the number 7 in base 10.

    So you could turn on the first 3 layers (and turn off all others) by doing either of the following two

    collision_layer = 7
    collision_layer = 0b0111

    They're the same thing.

    The method set_collision_layer_bit() is mostly a friendly tool for people who never used binary operators. Under the hood, it probably does a simple binary operation.

  • Luca Leonardi(LuxeL) replied

    All clear now, thank you for your explanation!