bool
内置布尔类型。
描述
布尔类型 bool 是内置的 Variant 类型,只能存储 true(真)和 false(假)的其中之一。你可以把它理解为开关,要么处于打开状态,要么处于关闭状态。也可以理解为二进制所使用的数字,只有 1 或者 0。
if 等条件语句中可以直接使用布尔值:
var can_shoot = true
if can_shoot:
launch_bullet()
bool canShoot = true;
if (canShoot)
{
LaunchBullet();
}
比较运算符返回的都是布尔值(==、>、<= 等)。没有必要比较布尔值本身,因此不需要在这些比较后面加上 == true 或 == false。
布尔值可以和逻辑运算符 and、or、not 组合,构成复杂的条件:
if bullets > 0 and not is_reloading():
launch_bullet()
if bullets == 0 or is_reloading():
play_clack_sound()
if (bullets > 0 && !IsReloading())
{
LaunchBullet();
}
if (bullets == 0 || IsReloading())
{
PlayClackSound();
}
注意:在现代编程语言中,逻辑运算符是按顺序求值的。如果后续条件不会对最终结果产生影响,那么就会跳过对这些条件的求值。这种行为叫作短路求值,在注重性能的场合能够避免对开销较大的条件进行求值。
注意:根据惯例,返回布尔值的内置方法和属性通常都以判断题、形容词等形式命名(String.is_empty()、Node.can_process()、Camera2D.enabled 等)。
构造函数
bool() |
|
运算符
operator !=(right: bool) |
|
operator <(right: bool) |
|
operator ==(right: bool) |
|
operator >(right: bool) |
构造函数说明
构造设置为 false 的 bool。
构造给定 bool 的副本。
将 float 值转换为布尔值。如果 from 等于 0.0(包括 -0.0)则返回 false,其他值则返回 true(包括 @GDScript.INF 和 @GDScript.NAN)。
将 int 值转换为布尔值。如果 from 等于 0 则返回 false,其他值则返回 true。
运算符说明
bool operator !=(right: bool) 🔗
如果两个布尔值不同则返回 true,即一个是 true、一个是 false 的情况。这个运算可以视为逻辑异或(XOR)。
bool operator <(right: bool) 🔗
如果左操作数为 false 且右操作数为 true,则返回 true。
bool operator ==(right: bool) 🔗
如果两个布尔值相同则返回 true,即都是 true 或都是 false 的情况。这个运算可以视为逻辑相等(EQ)或者同或(XNOR)。
bool operator >(right: bool) 🔗
如果左操作数为 true 且右操作数为 false,则返回 true。