how-to-make-a-video-game-in-unity-camera-follow

Course: 【油管100w+】 Unity 入门视频

《🎮 How to make a Video Game in Unity — CAMERA FOLLOW (E04)》

以下是系统化的 Notion 笔记版本(延续前几期的 🎮🏛🧭📦📚🧠🧪✅🪄 风格),

适合直接复制进 Notion,用作系列学习记录。


🎮 视频标题|How to make a Video Game in Unity — CAMERA FOLLOW (E04)

👤 主讲人|Brackeys

📅 系列定位|Unity 初学者系列 Episode 04

🏷 关键词|Camera Follow | Transform | Vector3 | Offset | Parenting | 组件引用


🏛 课程目标

让摄像机平滑跟随玩家移动,而不受玩家旋转影响。

学习 Transform 引用Vector3 向量偏移、与脚本化位置控制。


🧭 方法一:直接父子绑定(不推荐)

  • Main Camera 拖动到 Player 对象下 → Camera 成为 Player 的子对象。
  • 优点:位置自动跟随。
  • 缺点:当 Player 旋转或翻滚时,Camera 也会跟着旋转,画面混乱。

❌ 适用于固定视角或第一人称游戏,不适合独立第三人称视角。


📦 方法二:脚本跟随(推荐方案)

思路

让 Camera 通过脚本实时追踪 Player 的位置,只跟位置、不跟旋转。


🧠 创建脚本:FollowPlayer.cs

1️⃣ 在 Camera 上添加组件 → New Script → 命名 FollowPlayer

2️⃣ 双击打开脚本,删除 Start() 函数,只保留 Update()

3️⃣ 在脚本中写入:

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public Transform player;

    void Update()
    {
        // 摄像机位置 = 玩家位置
        transform.position = player.position;
    }
}
  • public Transform player; 用于在 Inspector 中指定目标(Player)。
  • transform 代表此脚本挂载对象(即 Camera)的 Transform 组件。
  • 每帧将 Camera 的位置同步为 Player 的位置。

🎯 Unity 设定:

  • 保存脚本 → 回到 Unity → 将 Player 拖入 player 插槽即可。

📚 测试:控制台验证玩家坐标

Debug.Log(player.position);
  • 每帧输出玩家的世界坐标。
  • 打开 Console 面板,可看到 Y 值因重力下降,Z 值随前进递增。
  • 验证脚本与对象引用正确。

🧪 问题:摄像机位于玩家体内

当前脚本让摄像机“紧贴”玩家中心 → 形成第一人称效果。

我们希望第三人称视角,即让相机稍微上移且后退


📦 引入偏移(Offset)变量

public Vector3 offset;

在 Inspector 中可设置:

  • X = 0(居中)
  • Y = 1(抬高)
  • Z = -5(后退)

Vector3 是存储三个 float 值的结构(x, y, z),用于表示空间坐标或方向。


🧭 应用偏移量:更新摄像机位置

transform.position = player.position + offset;

“+” 对 Vector3 的作用:逐分量相加,即:

(x₁+x₂, y₁+y₂, z₁+z₂)。

📘 示例:

若 Player 位置为 (0,1,6),Offset 为 (0,1,-5) →

Camera 位置 = (0, 2, 1)。

🎯 摄像机位于玩家正后方并稍微抬高,随玩家移动但保持距离。


最终脚本:FollowPlayer.cs

using UnityEngine;

public class FollowPlayer : MonoBehaviour
{
    public Transform player;
    public Vector3 offset;

    void Update()
    {
        transform.position = player.position + offset;
    }
}

🧩 效果:

  • 摄像机稳定跟随玩家运动。
  • 不受旋转干扰。
  • 保持固定距离(第三人称效果)。

🧠 核心原理回顾

概念说明
TransformUnity 中的“空间信息组件”,存储位置、旋转、缩放。
public 变量在 Inspector 中可编辑,可拖拽引用对象。
Vector3表示三维向量或坐标 (x, y, z)。
transform.position当前对象的位置。
player.positionPlayer 对象的位置。
offset预设的相对位移量。
+ 运算符重载允许直接相加两个 Vector3。

🪄 额外拓展(进阶可选)

  • 使用 LateUpdate() 替代 Update():可在玩家更新后再移动相机,避免抖动。

    void LateUpdate() {
        transform.position = player.position + offset;
    }
  • 想要平滑移动可使用:

    transform.position = Vector3.Lerp(transform.position, player.position + offset, 0.1f);
  • 想实现跟随旋转,可加入 transform.LookAt(player);


本集总结

步骤内容
1️⃣在 Camera 上创建 FollowPlayer.cs
2️⃣声明 public Transform player 以获取目标引用
3️⃣声明 public Vector3 offset 设置偏移
4️⃣Update()LateUpdate() 中更新位置
5️⃣在 Inspector 调整参数至满意的视角

📚 下一集预告:Boundaries & Falling Out

Episode 05 将加入边界检测与“游戏失败”判定,

当玩家掉落出场景时重新开始或结束游戏。