Unity Mathf 实用笔记

一、Math 和 Mathf 的区别

1. 基本区别

特性System.Math (C#)UnityEngine.Mathf (Unity)
精度double (64位)float (32位)
性能计算较慢,精度高计算更快,适合实时游戏
用途通用数学计算游戏开发优化
三角函数使用弧度使用弧度(但有Deg2Rad转换)

2. 使用建议

  • 游戏开发优先用 Mathf(性能优化)
  • 科学计算或需要高精度时用 Math

二、Mathf 常用API详解

1. 基本运算

(1) 绝对值
float abs = Mathf.Abs(-10.5f); // 10.5

应用场景:距离计算、速度方向无关的大小比较

(2) 取整
float f = 3.6f;
Mathf.Floor(f); // 3 (向下取整)
Mathf.Ceil(f);  // 4 (向上取整)
Mathf.Round(f); // 4 (四舍五入)

注意Round(3.5f) 可能返回4(银行家舍入法)

(3) 钳制函数 (Clamp)
// 限制值在min~max之间
float hp = Mathf.Clamp(currentHP, 0, maxHP);

// 限制在0~1之间(常用于标准化)
float normalized = Mathf.Clamp01(value);
(4) 最大/最小值
float max = Mathf.Max(3, 5, 2); // 5
float min = Mathf.Min(3, 5, 2); // 2
(5) 幂运算
float square = Mathf.Pow(2, 3); // 8 (2的3次方)
float sqrt = Mathf.Sqrt(16);    // 4 (平方根)

2. 三角函数

(1) 基本函数
// 注意:参数必须是弧度!
float sin = Mathf.Sin(Mathf.PI/2); // 1 (90度)
float cos = Mathf.Cos(Mathf.PI);   // -1 (180度)
(2) 角度/弧度转换
// 角度 → 弧度
float radians = 30 * Mathf.Deg2Rad;

// 弧度 → 角度
float degrees = Mathf.PI * Mathf.Rad2Deg; // 180
(3) 反三角函数
// 计算角度(返回弧度)
float angle = Mathf.Atan2(dy, dx); // 两点间角度

三、Lerp 函数深度解析

1. 基本语法

float lerpedValue = Mathf.Lerp(start, end, t);
  • start: 起始值
  • end: 目标值
  • t: 插值系数 (0~1)

2. 工作原理

Lerp 是线性插值,计算公式:

result = start + (end - start) * t

t=0 返回 startt=1 返回 end

3. 经典应用场景

(1) 平滑移动
// 每帧移动50%的距离
transform.position = Vector3.Lerp(
    currentPos, 
    targetPos, 
    0.5f * Time.deltaTime
);
(2) 颜色渐变
Color newColor = Color.Lerp(red, blue, t);
(3) 相机跟随(延迟效果)
void Update() {
    camera.position = Vector3.Lerp(
        camera.position,
        player.position,
        2f * Time.deltaTime
    );
}

4. 进阶技巧

(1) 加速/减速效果
// 使用SmoothStep实现平滑过渡
float t = Mathf.SmoothStep(0, 1, progress);
(2) 无限接近(阻尼效果)
// 永远无法到达终点,但无限接近
float lerped = Mathf.Lerp(current, target, 0.1f);
(3) 非0~1范围的t值
// t可以超出[0,1]范围实现"外推"
float extended = Mathf.Lerp(0, 10, 1.5f); // 15

5. 常见误区

// ❌ 错误用法:直接这样写会导致越来越慢
transform.position = Lerp(transform.position, target, 0.1f);

// ✅ 正确用法:配合Time.deltaTime
float speed = 2f;
transform.position = Lerp(current, target, speed * Time.deltaTime);

四、总结对比表

需求推荐API备注
游戏对象移动Mathf.Lerp配合Time.deltaTime使用
角度计算Mathf.Sin/Cos记得用Deg2Rad转换
数值限制Mathf.Clamp防止数值溢出
平滑过渡Mathf.SmoothStep比Lerp更自然的缓动
性能敏感区域Mathf所有函数Math快约30%

📌 黄金法则

  1. 游戏逻辑优先用Mathf
  2. 三角函数参数永远用弧度
  3. Lerpt参数通常需要乘以Time.deltaTime
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值