signf
2026/4/15大约 3 分钟
最后同步日期:2026-04-15 | Godot 官方原文 — signf
signf
定义
浮点数符号函数。给它一个数字,它只告诉你这个数字的"方向",而不关心它有多大。
具体来说:
- 正数(不管多大)-> 返回
1.0 - 负数(不管多小)-> 返回
-1.0 - 零 -> 返回
0.0
打个比方:signf 就像马路上的路标指示器——它只告诉你"该往哪个方向走",而不关心"要走多远"。正数朝右走(+1),负数朝左走(-1),零就是原地不动(0)。
在游戏开发中,signf 常用于:
- 判断角色应该朝左还是朝右移动
- 确定速度或力的方向(不管大小)
- 把一个可能很大的数值"压缩"成只有三个状态的判断结果
函数签名
C#
// 方式一:使用 Godot 的 Mathf(返回 int)
public static int Sign(float x)
public static int Sign(double x)
// 方式二:使用 .NET 标准库(返回 int)
public static int Sign(float x)
public static int Sign(double x)
public static int Sign(int x)
public static int Sign(long x)GDScript
func signf(x: float) -> float参数说明
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
x | float | 是 | 要判断符号的浮点数 |
返回值
- GDScript:返回
float类型的符号值(1.0、-1.0或0.0) - C#:返回
int类型的符号值(1、-1或0)
输入 x | 返回值 |
|---|---|
x > 0(正数) | 1 / 1.0 |
x < 0(负数) | -1 / -1.0 |
x == 0(零) | 0 / 0.0 |
代码示例
C#
using Godot;
using System;
public partial class SignExample : Node
{
// 导出属性:角色的移动速度
[Export] public float ExMoveSpeed = 200f;
// 内部变量:当前水平输入方向
private float _horizontalInput = 0f;
public override void _Ready()
{
// 基本用法:判断数字的符号
GD.Print(Mathf.Sign(5.0f)); // 输出: 1
GD.Print(Mathf.Sign(-3.7f)); // 输出: -1
GD.Print(Mathf.Sign(0.0f)); // 输出: 0
}
public override void _Process(double delta)
{
// 实际应用:根据输入方向移动角色
// signf 只关心方向,不关心按键按了多深
float direction = Mathf.Sign(_horizontalInput);
// 如果有输入才移动
if (direction != 0)
{
// 用方向乘以速度,得到固定速度的移动
float velocity = direction * ExMoveSpeed;
GD.Print("移动方向: ", direction, " 速度: ", velocity);
}
}
}GDScript
extends Node
@export var ex_move_speed: float = 200.0
var _horizontal_input: float = 0.0
func _ready():
# 基本用法:判断数字的符号
print(signf(5.0)) # 输出: 1.0
print(signf(-3.7)) # 输出: -1.0
print(signf(0.0)) # 输出: 0.0
func _process(delta):
# 实际应用:根据输入方向移动角色
# signf 只关心方向,不关心按键按了多深
var direction = signf(_horizontal_input)
# 如果有输入才移动
if direction != 0:
# 用方向乘以速度,得到固定速度的移动
var velocity = direction * ex_move_speed
print("移动方向: ", direction, " 速度: ", velocity)注意事项
- 返回类型差异:GDScript 的
signf()返回float,而 C# 的Mathf.Sign()返回int。如果你在 C# 中需要浮点结果,需要手动转换:(float)Mathf.Sign(x)。 - 零的特殊处理:当输入恰好为
0.0时,返回0。但在实际使用中,由于浮点数精度问题,一个"理论上为零"的值可能是一个极小的正数或负数,这时signf会返回1或-1。如果你需要处理"接近零"的情况,可以配合is_zero_approx()使用。 - 与
sign和signi的区别:Godot 提供了三个符号函数——sign()接受任意类型,signf()专门处理浮点数并返回浮点数,signi()专门处理整数并返回整数。在 GDScript 中,signf()是处理浮点数时的明确选择。
