Unity中Mathf的常见使用
弧度和度
先了解弧度?
- 弧度是角的度量单位。
- 弧长等于半径的弧,其所对的圆心角为1弧度
- 一周的弧度数为 2πr/r = 2π ,360°角=2π弧度,因此,1弧度约为57.3°
弧度和度的转换
- 求弧度
public float deg = 30.0F;
float rad = deg * Mathf.Deg2Rad;
- 求角度
float rad = 1.0f;
float deg = rad * Mathf.Rad2Deg;
Mathf.Atan2
描述
- 根据坐标求角度(分弧度和度两种单位)
- 返回其 Tan 为 y/x 的**角度**(以弧度为单位)。
- 返回值是 X 轴与 2D 向量(从零开始,在 (x,y) 处终止)之间的 角度。
举例用法
- 使用 Mathf.Atan2() 计算点与 X轴 的夹角的弧度。
A、B 两个点。
Vector2 A = new Vector2(x, y);
Vector2 B = new Vector2(x, y);
var radian = Mathf.Atan2(B.y - A.y, B.x - A.x);
角色移动实战
描述
在使用CharacterController组件的Move方法进行移动,需传入一个位移的Vector3向量
代码示例
v = Input.GetAxisRaw("Horizontal");//获取按键输入-1~1
h = Input.GetAxisRaw("Vertical");
//单位化,防止同时两个方向移动,速度变快
Vector3 direction = new Vector3(v, 0, h).normalized;
//计算按键后的,需要的转向角度,这以人物前方为初始点,x/y。
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg
//在加上相机的角度,实现相对相机的前方的移动
+ Camera.main.transform.localEulerAngles.y
//人物旋转
transform.rotation = Quaternion.Euler(0, targetAngle, 0);
//考虑到旋转的平滑的用插值运算
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
//人物移动,默认是正前方。上面根据输入得到旋转角度
moveDir = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
这个就是得到的最终移动的位置。
//Quaternion与Vector3的右乘操作(*)返回一个将原有向量做旋转操作后的新向量
Mathf.Tan
描述
- 返回角度 f 的正切(以弧度为单位),
求距离
相机旋转实战
代码示例
鼠标上下控制相机的上下移动
followYAngle += Input.GetAxis("Mouse Y");
限制角度在60
followYAngle = Mathf.Clamp(followYAngle, 5, 60);
Y=Mathf.Tan(Mathf.Deg2Rad * followYAngle)*X;
Mathf.Ceil
描述
向上取整
- 返回大于或等于 f 的最小整数。
示例
// Prints 10
Debug.Log(Mathf.Ceil(10.0F));
// Prints 11
Debug.Log(Mathf.Ceil(10.2F));
Mathf.Floor
描述
向下取整
- 返回小于或等于 f 的最大整数。
Debug.Log(Mathf.Floor(10.2F)); // Prints 10
Debug.Log(Mathf.Floor(10.7F)); // Prints 10
其他常见
静态函数 | 描述 |
---|---|
Abs (float f) | 返回f的绝对值 |
Clamp (float value, float min, float max) | 限制值在两个浮点数之间 |
Exp (float power) | 返回 e 的指定幂。 |
Lerp (float a, float b, float t) | 在 a 与 b 之间按 t 进行线性插值 |
Sqrt (float f) | 返回 f 的平方根。 |