摄像机控制与视野

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; // 视野角度

// 正交模式(无透视效果,适合 2D 游戏)
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.LerpQuaternion.Slerp 实现平滑过渡
  • 鼠标锁定时用 Cursor.lockState 控制
  • 多摄像机通过 Viewport Rect 和 Depth 实现分屏/小地图

练习题

  1. 实现第三人称跟随摄像机,支持鼠标拖拽旋转视角
  2. 实现第一人称视角的鼠标控制(水平旋转身体,垂直旋转摄像机)
  3. 制作一个正交小地图摄像机,跟随玩家
  4. 实现摄像机缩放功能(鼠标滚轮控制距离或 FOV)
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Unity3D开发基础教程 系列
第 10/20 篇
分享: