场景管理与坐标系统

5.1 场景(Scene)的概念

场景是 Unity 中组织和编辑游戏内容的基本单位。一个场景可以包含:

  • 游戏物体(GameObject)
  • 灯光和摄像机
  • UI 元素
  • 音频源
  • 导航网格

游戏由多个场景组成,常用于:

  • 不同关卡
  • 主菜单和游戏画面
  • 加载界面

5.2 场景管理

场景操作 API

1
2
3
4
5
6
7
8
using UnityEngine.SceneManagement;

// 获取当前活动场景
Scene currentScene = SceneManager.GetActiveScene();
Debug.Log($"场景名称:{currentScene.name}");
Debug.Log($"场景索引:{currentScene.buildIndex}");
Debug.Log($"是否已加载:{currentScene.isLoaded}");
Debug.Log($"根物体数量:{currentScene.rootCount}");

加载场景

1
2
3
4
5
6
7
8
9
10
11
12
13
// 通过名称加载(单例模式,卸载当前场景)
SceneManager.LoadScene("Level2");

// 通过 Build Index 加载
SceneManager.LoadScene(1);

// 异步加载(配合加载界面)
AsyncOperation operation = SceneManager.LoadSceneAsync("Level2");
operation.allowSceneActivation = false; // 延迟激活

// 等待加载完成
yield return new WaitUntil(() => operation.progress >= 0.9f);
operation.allowSceneActivation = true;

场景需要在 File → Build Settings 中添加到 Build 列表才能通过索引加载。

多场景加载

1
2
3
4
5
// 叠加模式加载(不卸载当前场景)
SceneManager.LoadScene("UI_Overlay", LoadSceneMode.Additive);

// 卸载指定场景
SceneManager.UnloadSceneAsync("UI_Overlay");

5.3 坐标系统

Unity 使用左手坐标系

  • X 轴:向右
  • Y 轴:向上
  • Z 轴:向前(屏幕内)

世界坐标 vs 本地坐标

1
2
3
4
5
6
7
8
9
10
11
// 世界坐标(场景中的绝对位置)
Vector3 worldPos = transform.position;

// 本地坐标(相对父级的偏移)
Vector3 localPos = transform.localPosition;

// 将世界坐标转换为本地坐标
Vector3 localFromWorld = transform.InverseTransformPoint(worldPoint);

// 将本地坐标转换为世界坐标
Vector3 worldFromLocal = transform.TransformPoint(localPoint);

5.4 Vector3 常用操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 向量
Vector3 forward = Vector3.forward; // (0, 0, 1)
Vector3 up = Vector3.up; // (0, 1, 0)
Vector3 right = Vector3.right; // (1, 0, 0)

// 计算距离
float dist = Vector3.Distance(posA, posB);

// 方向归一化
Vector3 dir = (targetPos - transform.position).normalized;

// 线性插值
Vector3 middle = Vector3.Lerp(posA, posB, 0.5f); // 中点
Vector3 smooth = Vector3.Lerp(current, target, Time.deltaTime * 2f); // 平滑跟随

// 点乘(判断前后)
float dot = Vector3.Dot(transform.forward, direction);

// 叉乘(判断左右)
Vector3 cross = Vector3.Cross(transform.forward, direction);

5.5 四元数与旋转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 四元数创建旋转
Quaternion rotation = Quaternion.Euler(0, 90, 0); // 绕 Y 轴转 90 度

// 看向目标
transform.rotation = Quaternion.LookRotation(direction);

// 平滑旋转
transform.rotation = Quaternion.Slerp(
transform.rotation,
targetRotation,
Time.deltaTime * 5f
);

// 旋转差值
Quaternion delta = Quaternion.FromToRotation(Vector3.up, hit.normal);

5.6 本章小结

  • 场景是游戏内容的组织单位,通过 SceneManager 加载/卸载
  • Unity 使用左手坐标系,Y 轴向上
  • 理解世界坐标与本地坐标的区别
  • Vector3 提供丰富的向量运算方法
  • 旋转操作使用 Quaternion(四元数)避免万向锁

练习题

  1. 创建两个场景 Scene1 和 Scene2,实现按空格键切换
  2. 在脚本中使用 Vector3.Lerp 让物体平滑移动到目标位置
  3. 练习 TransformPointInverseTransformPoint,理解坐标转换
  4. 使用 Quaternion.Slerp 实现炮塔平滑转向目标
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Unity3D开发基础教程 系列
第 5/20 篇
分享: