Math in Unity : Grid and Bitwise operation (Part V)

Matteo Lo Piccolo
3 min readOct 5, 2021

Now that we have seen the operators between bits, we can code the example of the orange door.

The logic would be this:
_orangeDoor = _yellowKey + _redKey;

With operators become this
_orangeDoor = _yellowKey | _redKey;

Let’s look at logic pieces by pieces.
_orangeDoor in number is 3, in bit is 0 0 1 1

Now, we set the flag to _orangeDoor when we have
_yellowKey, wich is 2 in number and 0 0 1 0 in bits
and
_redKey, wich is 1 in number and 0 0 0 1 in bits

With the OR operator, the sequence check happens like this
0 0 1 0
0 0 0 1
And the result is…
Do you remember?
The OR operator check values and return 1 IF ANY OF TWO BITS ARE 1.
So this is what returns
0 0 1 1

Now this approach can be used for multiple purposes.
I gave the example of the doors, but you can also take an RPG as an example.
RPGs usually have many stats, such as strength, dexterity, intelligence, charisma, etc.
With the same principle it is possible to associate the various statistics to a number / bit
and make the various checks to be able to use spells or other.

Again, we keep everything really simple.

Now, just like with doors, you might need to check two stats at the same time.
Let’s create a variable again and associate the two statistics we need

If, in addition to these two statistics, a further check is needed, perhaps on the constitution, we could use this syntax

By doing so we add a check to our number / bits.

If we split again the logic, the result is this:
statistics now is 12, _dexterity 8 + _strenght 4

In bits
0 1 0 0 wich is 4
1 0 0 0 wich is 8

Statistics now is 12 in number
1 1 0 0 in bits

statistics |= _constitution means :
Statistics now is 28 in number because the bits sequence is this

0 1 1 0 0
1 0 0 0 0

the result is
1 1 1 0 0

The same things is simple this :
statistics += _constitution

This is to add, to remove we can do this:
statistics &= ~_strenght;

How does this work?
Ok, let’s do all the steps and see what happens.

statitistic is 12, 4+ 8
0 1 1 0 0
then we add 16, so now we have 28
1 1 1 0 0

Let’s pay attention to this step:
_strenght is
0 0 1 0 0
BUT

~_strengh is
1 1 0 1 1
because the NOT OPERATOR takes one number and inverts all bits of it

Then we have to check statistic with ~_strengh
1 1 1 0 0
1 1 0 1 1

Because we use &= operator, it returns 1 only if both bits are 1.
1 1 0 0 0

In number is :
0 1 1 0 0 (which is 12)
1 1 1 0 0 (which is 28)

1 1 0 1 1 (IS NOT STRENGHT)

And after check the sequences
1 1 0 0 0 (which is 24)

To better understand, all of the above is equal to
statistics -= _strenght;

In the next lecture we see more things with bitwise operations!

--

--

Matteo Lo Piccolo

Always in love with programming, even if late (I'm already 39 years old) I decided to follow my dream! We will see how far my passion will take me!