10.1 Camera 组件
Camera 是玩家观察游戏世界的窗口,每个场景至少需要一个 Camera。
核心属性
| 属性 |
说明 |
| Clear Flags |
背景填充方式(Skybox/Solid Color/Depth Only) |
| Background |
纯色背景颜色 |
| Projection |
Perspective(透视)/ Orthographic(正交) |
| Field of View |
视野角度(透视模式,默认 60°) |
| Clipping Planes |
Near/Far 裁剪面(近裁面/远裁面) |
| Viewport Rect |
视口矩形(支持分屏) |
| Depth |
深度值(多个摄像机的渲染顺序) |
10.2 正交 vs 透视
1 2 3 4 5 6 7 8 9
| Camera cam = GetComponent<Camera>();
cam.orthographic = false; cam.fieldOfView = 60f;
cam.orthographic = true; cam.orthographicSize = 5f;
|
| 对比项 |
透视 |
正交 |
| 视觉效果 |
近大远小 |
无透视变形 |
| 适用场景 |
3D 游戏 |
2D 游戏、UI、地图 |
| 核心参数 |
Field of View |
Orthographic Size |
| 视野含义 |
角度(度) |
高度(世界单位) |
10.3 摄像机跟随
简单跟随
1 2 3 4 5 6 7 8 9 10 11
| public class CameraFollow : MonoBehaviour { [SerializeField] private Transform target; [SerializeField] private Vector3 offset = new Vector3(0, 5, -10);
void LateUpdate() { transform.position = target.position + offset; } }
|
平滑跟随
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class SmoothCameraFollow : MonoBehaviour { [SerializeField] private Transform target; [SerializeField] private Vector3 offset = new Vector3(0, 5, -10); [SerializeField] private float smoothSpeed = 5f;
void LateUpdate() { Vector3 desiredPos = target.position + offset; transform.position = Vector3.Lerp( transform.position, desiredPos, smoothSpeed * Time.deltaTime );
transform.LookAt(target); } }
|
10.4 鼠标控制视野
第一人称视角
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class FirstPersonCamera : MonoBehaviour { [SerializeField] private Transform playerBody; [SerializeField] private float mouseSensitivity = 100f; private float xRotation = 0f;
void Start() { Cursor.lockState = CursorLockMode.Locked; }
void Update() { float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 90f); transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX); } }
|
10.5 多摄像机与分屏
1 2 3 4 5 6 7 8 9 10 11
| Camera player1Cam = GetComponent<Camera>(); player1Cam.rect = new Rect(0, 0, 0.5f, 1);
Camera player2Cam = otherCamera; player2Cam.rect = new Rect(0.5f, 0, 0.5f, 1);
Camera minimapCam = minimapCamera; minimapCam.rect = new Rect(0.8f, 0.8f, 0.2f, 0.2f); minimapCam.depth = 1;
|
10.6 本章小结
- Camera 是游戏视角,支持透视/正交两种投影模式
LateUpdate 中实现摄像机跟随,避免抖动
Vector3.Lerp 和 Quaternion.Slerp 实现平滑过渡
- 鼠标锁定时用
Cursor.lockState 控制
- 多摄像机通过 Viewport Rect 和 Depth 实现分屏/小地图
练习题
- 实现第三人称跟随摄像机,支持鼠标拖拽旋转视角
- 实现第一人称视角的鼠标控制(水平旋转身体,垂直旋转摄像机)
- 制作一个正交小地图摄像机,跟随玩家
- 实现摄像机缩放功能(鼠标滚轮控制距离或 FOV)