What are multi-conditional booleans?
Multi-Conditional booleans, as the name suggests, are bool values that can be true or false under multiple conditions. For example, in your game you might have conditions under which your player character is invincible. Let's consider two states: The player is invincible if they are equipped with a Shield or they are invincible for 5 seconds after they choose to Revive in the game.
What happens if you implement these with a single boolean?
Suppose you have a boolean called _invincible that is set to true or false depending on the current player state. Now the player dies in the game and chooses to Revive. You set the bool value to true. Now before 5 seconds elapse, the player equips the Shield. You again set the boolean to true (or you may check if it's already true and not set it to the same value). After 5 seconds of Revive elapse you set the boolean to false, and now we have a problem. The player is equipped with a Shield and is NOT invincible.
How do multi-conditional booleans help with this?
Multi-conditional boolean is a wrapper class, that uses bitwise operations to determine the final state of the boolean. We reserve bits of an integer, one for each condition under which the player can be invincible. In the example above, we will reserve the first bit for Revive and the second bit for Shield. We set the corresponding bit to '1' or '0' depending on if that particular condition is true or false. The multi-conditional boolean is false when all the bits are set to 0, i.e the integers value is 0. If it is greater than 0 then the multi-conditional boolean is true.
In the following tutorial, I show you how to implement multi-conditional booleans in your games using Unity and C#.
P.S: For more tutorials and game dev content please SUBSCRIBE!
Top comments (2)
java based example without multi-condition
boolean isInvincible = hasShield() || hasRevived();
public boolean hasShield() {
return getInventory().hasEquipped(Items.SHIELD);
}
public boolean hasRevived() {
return getStatus().hasEffect(Effects.REVIVED);
}
This gets rid of having to manually set or reset the state, and avoids creating more classes with basic functionality.
Hey! Thanks for the reply. Well, the shield and revive were just general examples. If the conditions under which the player is invincible keep increasing with more boosts or bonuses, you will have to keep adding to that OR condition list and can get messy after a point. And this is just one case in your entire game. You can have other booleans which might need to check multiple conditions. With the multi-conditional boolean generic class all you have to do is create a new Enum value for a new condition and just call Set and Reset with that value on the multi-conditional boolean.
Also, you don't have to create any more classes but just the one Multi-Conditional boolean generic class and it works wonders. But it's just my opinion, not trying to say what you doing is wrong.