A* Pathfinding Project
4.2.0
The A* Pathfinding Project for Unity 3D
|
A short tutorial on bitmasks.
There are several bitmasks used in various places in the package. These may not be familiar to all users, so in this tutorial I will briefly explain how they are used.
A bitmask is a very efficent way to represent a set of options that can be enabled or disabled. A common example that is used both in Unity and in this package is layer masks. Layer masks represent a set of layers. For example if you have a light, you could set a layer mask to determine which layers that it should cast a light on. In this package layer masks are used for: selecting sets of layers to use, sets of graphs, sets of tags and sets of RVO layers.
A bitmask is represented in a single number, usually a 32-bit integer. Since we have 32 bits in that number this means that we have 32 options that we can turn on and off.
For simplicity, lets say we have a 3 bit number and 3 options: "A", "B" and "C". In this 3 bit number we can use the first bit to determine if option "A" is enabled, the second bit to determine if "B" is enabled, and the last bit for "C". For example the number 6 which is 110 in binary means that "A" and "B" are enabled, but "C" is disabled. 2 or 010 in binary would mean that only option "B" is enabled. In the same way we can use this for 32-bit numbers.
In code you can easily create bitmasks using bitshifts and bitwise-or.
A bitshift essentially just moves some bits in a direction.
A bitwise-or will just set a bit to 1 if the bit was 1 in either of the 2 numbers.
If we want to enable option 0, 3 and 4 we can construct individual bitmasks for enabling the options separately and then OR the bitmasks together.
The value -1 is represented in binary as all 1s. So -1 means that all options are enabled. Similarly the value 0 means no options are enabled.
For more information check out the Wikipedia article on the subject.
The most common use of bitmasks in the package is for selecting which graphs are going to be searched when querying for the closest node to a point. The NNConstraint class has a field called 'graphMask' which determines which graphs are going to be searched.
The Seeker.StartPath method also takes a parameter called 'graphMask' which is just forwarded to the Path.nnConstraint object. It can be used in the same way.