7.1 物理引擎概述
Unity 内置 PhysX(3D)和 Box2D(2D)物理引擎,提供:
- 刚体动力学(力、质量、速度)
- 碰撞检测
- 关节和约束
- 射线检测
7.2 Rigidbody 组件
基本属性
| 属性 |
说明 |
| Mass |
质量(默认 1kg) |
| Drag |
线性阻力(空气阻力) |
| Angular Drag |
角阻力 |
| Use Gravity |
是否受重力影响 |
| Is Kinematic |
启用后不受物理力驱动,可用 Transform 控制 |
| Constraints |
锁定位置/旋转轴 |
添加刚体
1 2 3 4 5 6 7 8 9
| public class PhysicsDemo : MonoBehaviour { private Rigidbody rb;
void Start() { rb = GetComponent<Rigidbody>(); } }
|
7.3 力的应用
1 2 3 4 5 6 7 8 9 10 11
| rb.AddForce(Vector3.forward * 10f, ForceMode.Force);
rb.AddForce(Vector3.up * 5f, ForceMode.Impulse);
rb.AddForce(Vector3.forward * 10f, ForceMode.Acceleration);
rb.AddForce(Vector3.forward * 10f, ForceMode.VelocityChange);
|
力矩和旋转
1 2 3 4 5
| rb.AddTorque(Vector3.up * 10f);
rb.AddForceAtPosition(Vector3.forward * 10f, transform.position + Vector3.right);
|
7.4 刚体运动控制
1 2 3 4 5 6 7 8 9 10 11
| rb.velocity = new Vector3(h, rb.velocity.y, v) * speed;
rb.angularVelocity = Vector3.up * rotateSpeed;
rb.MovePosition(targetPos);
rb.MoveRotation(targetRot);
|
推荐:物理相关操作放在 FixedUpdate 中,以获得稳定的物理步长。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| void FixedUpdate() { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical");
Vector3 move = (transform.right * h + transform.forward * v) * speed; rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded()) { rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse); } }
bool IsGrounded() { return Physics.Raycast(transform.position, Vector3.down, 1.1f); }
|
7.5 物理材质
物理材质(Physic Material)控制表面的摩擦力和弹性。
| 属性 |
说明 |
| Dynamic Friction |
运动摩擦力 |
| Static Friction |
静摩擦力 |
| Bounciness |
弹性系数(0~1) |
| Friction Combine |
摩擦力叠加模式(Average/Min/Max/Multiply) |
| Bounce Combine |
弹性叠加模式 |
创建方式:Project 面板 → Create → Physic Material
7.6 射线检测
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hit, 100f)) { Debug.Log($"击中物体:{hit.collider.name}"); Debug.Log($"击中点:{hit.point}"); Debug.Log($"法线方向:{hit.normal}"); }
Collider[] targets = Physics.OverlapSphere(transform.position, 5f); foreach (Collider target in targets) { if (target.CompareTag("Enemy")) { target.GetComponent<Enemy>().TakeDamage(10); } }
|
7.7 本章小结
- Rigidbody 让物体受物理引擎控制
AddForce / velocity / MovePosition 三种移动方式各有适用场景
- 物理操作放在
FixedUpdate 中
- Physic Material 控制摩擦和弹性
Physics.Raycast 和 OverlapSphere 实现检测功能
练习题
- 创建几个不同质量的球体,从高处落下观察碰撞效果
- 实现一个可推动方块的角色(用
AddForce 和 velocity 两种方式对比)
- 使用 Physic Material 制作一个弹跳球
- 实现鼠标点击发射射线,在点击位置生成一个球体