Math in Unity : Grid and Bitwise operation (Part VII)
Today we will see how to associate our “bits” to the grid with some formulas.
To start I set up an Array of cubes of various colors to compose our grid.
My simple goal for now is to create a variable for the red cells and keep track of it every time I create the grid.
The we have to create a bit to associate with each color, in order to keep track of it on the grid.
First of all, the formula for calculating the index is this:
row * width + column.
It means that if we have such a scenario:
0 0 0 0
0 0 1 0
0 0 0 0
0 0 0 0
The formula above is
1 * 4 + 2 = 6
If it looks wrong, remember:
the index starts from ZERO, so we have 1 for the row,
4 is a width in this example, because this is a 4 * 4 grid,
and 2 for the column.
I hope this make things clear.
But the point is:
how can we have a 1 in position 6 to be able to check if there is something on the tile, for example the Player?
One thing we can do is set the state of the Tile.
With this we create a new “newBit” card and calculate its position, after which we compare it with the bit that we pass to it as a parameter with the bitwise operator OR |=
P.S. Also, we will use a bool method which will return true or false depending on whether the tile bit is 1 (true) or false (0)
We won’t use it now, but we will need it in future articles
Let’s do a quick test and see what we got.
First of all, my grid is like this.
Nothing complex, just colored cubes.
Now, let’s see how to interact with the bits
The first thing to do is to create a long to encode a tile type.
I’ll try for the red cells.
P.S. We will use long simply because the grid is 64 tiles, and the long is 64 bits.
We will then create a tag for our red cell
Now, in our Start () creation loop, let’s check
Set the Tile state to RedTile
To check that everything went well, let’s put a simple Debug.Log (or create a method with a Debug inside) and see what happens
As we can see, the bit code keeps track of every red tile that is part of our grid!
Being completely Random we will have different results, but the principle is absolutely the same.
If you want to do other tests, for example for all colored cells, always remember to create a new long for each type of tile, and obviously the tag.