
FMath是 Unreal Engine 提供的数学工具类里面集中放置了大量常用数学函数例如取最大值、最小值限制数值范围绝对值随机数插值三角函数开方、乘方浮点数比较基本写法int32 Result FMath::Max(10, 20);1.最值MaxMinint32 Result FMath::Max(10, 20);int32 Result FMath::Min(10, 20);2.Clamp 限制数值范围FMath::Clamp(当前值, 最小值, 最大值);float Health 120.0f; Health FMath::Clamp(Health, 0.0f, 100.0f);最后Health返回100.0f。3.Abs 绝对值float Result FMath::Abs(-15.0f);4.RandRange、FRand随机数生成指定范围的随机数int32 RandomNumber FMath::RandRange(1, 10);float RandomNumber FMath::RandRange(0.0f, 100.0f);整数版本通常包含最大值FRand生成0.0f到1.0f之间的随机浮点数float RandomValue FMath::FRand();5.Lerp 线性插值FMath::Lerp(起始值, 目标值, 比例);例FMath::Lerp(0.0f, 100.0f, 0.0f); // 0 FMath::Lerp(0.0f, 100.0f, 0.25f); // 25 FMath::Lerp(0.0f, 100.0f, 0.5f); // 50 FMath::Lerp(0.0f, 100.0f, 1.0f); // 100向量插值FVector StartLocation(0.0f, 0.0f, 0.0f); FVector EndLocation(1000.0f, 0.0f, 0.0f); FVector NewLocation FMath::Lerp( StartLocation, EndLocation, 0.5f );6.FInterpTo 插值移动函数让浮点数平滑地接近目标值地插值函数距离目标越远变化越快距离目标越近变化越慢。float NewValue FMath::FInterpTo(Current,Target,DeltaTime,InterpSpeed);7.IsNearlyEqual 浮点数比较由于计算机底层原理float A 0.1f 0.2f;float B 0.3f;A和B在底层不一定完全相等UE提供FMath::IsNearlyEqual()也可以指定误差if (FMath::IsNearlyEqual(A, B, 0.001f)){}IsNearlyZero 判断一个浮点数是否接近0float Speed 0.00001f; if (FMath::IsNearlyZero(Speed)) { UE_LOG(LogTemp, Warning, TEXT(速度接近0)); }8.平方、开方、乘方float Result FMath::Square(5.0f);//平方float Result FMath::Sqrt(25.0f);//平方根float Result FMath::Pow(2.0f, 3.0f);//乘方9.三角函数float SinValue FMath::Sin(Angle);float CosValue FMath::Cos(Angle);float TanValue FMath::Tan(Angle);注意传入值是弧度不是角度转换float Radians FMath::DegreesToRadians(90.0f);float Result FMath::Sin(Radians);10.Round、Floor、Ceil浮点数处理四舍五入int32 Result FMath::RoundToInt(3.6f);向下取整int32 Result FMath::FloorToInt(3.9f);向上取整int32 Result FMath::CeilToInt(3.1f);去掉小数部分int32 Result FMath::TruncToInt(3.9f);11.Sign 获取正负号float Result FMath::Sign(-20.0f);正数返回1.0f负数返回-1.0f12.Wrap 循环限制数值float Angle FMath::Wrap(450.0f, 0.0f, 360.0f);返回9013.MapRangeClamped 映射数值范围将一个范围中的数值转换到另一个范围float Health 50.0f; float Percent FMath::GetMappedRangeValueClamped( FVector2D(0.0f, 100.0f), FVector2D(0.0f, 1.0f), Health );映射函数适用于更复杂的范围例如将传感器数值0~1023映射为物体缩放1~3