Unity 3D中如何实现《神庙逃亡》同款角色跟随相机效果
Unity实现《神庙逃亡》风格相机跟随方案
核心行为匹配规则
要完全对齐《神庙逃亡》的相机体验,需要严格满足三个核心约束:
- 玩家沿路径前进方向移动时,相机同步跟随,保持稳定的观察距离
- 玩家做左右车道切换(侧向位移)时,相机完全不响应这部分位移,保持当前视角的横向位置固定
- 路径发生90度转弯时,相机以平滑旋转的方式适配新的前进方向,无生硬跳变
关键实现设计
- 解耦相机与玩家的父子关系:绝对不能将相机作为玩家的子物体,否则侧向移动时相机会被强制带动
- 侧向位移过滤:计算相机目标位置时,将位置差在相机右轴(即视角的左右方向)的分量全部剔除,仅保留前进方向的位移作为跟随依据
- 平滑插值:前进方向的位置跟随用阻尼插值,航向旋转用四元数球面插值,避免抖动和硬转
- 更新时机:所有相机计算逻辑放在
LateUpdate中执行,确保在玩家移动逻辑执行完成后再计算相机位置,杜绝视角抖动
参考C#实现脚本
using UnityEngine; public class TempleRunCameraFollow : MonoBehaviour { [Header("跟随参数配置")] [Tooltip("相机相对于玩家的本地空间偏移(斜后方抬高视角)")] public Vector3 baseOffset = new Vector3(0f, 4.5f, -7.5f); [Tooltip("前进方向位置跟随的阻尼系数")] public float followSmoothSpeed = 6f; [Tooltip("航向旋转的平滑插值速度")] public float rotateSmoothSpeed = 1.2f; [Tooltip("是否开启侧向位移过滤(匹配神庙逃亡左右换道不跟拍的逻辑)")] public bool ignoreLateralMove = true; private Transform player; private Vector3 followVelocity; // SmoothDamp 方法需要的临时速度缓存 void Start() { // 自动绑定Tag为Player的目标对象,也可直接在Inspector面板拖拽赋值 player = GameObject.FindGameObjectWithTag("Player").transform; // 初始化相机位置,避免场景启动时的视角跳变 transform.position = player.position + player.rotation * baseOffset; transform.rotation = Quaternion.LookRotation(player.position - transform.position, Vector3.up); } void LateUpdate() { if (player == null) return; // 1. 平滑匹配玩家航向,实现90度转弯时的平滑旋转效果 Quaternion targetRot = player.rotation; transform.rotation = Quaternion.Slerp(transform.rotation, targetRot, rotateSmoothSpeed * Time.deltaTime); // 2. 计算玩家位置对应的相机基础目标位置 Vector3 rotatedOffset = player.rotation * baseOffset; Vector3 targetPos = player.position + rotatedOffset; // 3. 过滤侧向位移:剔除左右方向的位置差,仅保留前进方向的跟随分量 if (ignoreLateralMove) { Vector3 posDelta = targetPos - transform.position; float lateralComponent = Vector3.Dot(posDelta, transform.right); // 移除横向分量,剩下的就是纯前进方向的位移差 targetPos -= transform.right * lateralComponent; } // 4. 阻尼平滑移动相机,避免视角抖动 transform.position = Vector3.SmoothDamp( current: transform.position, target: targetPos, currentVelocity: ref followVelocity, smoothTime: 1f / followSmoothSpeed ); } }
使用注意事项
- 将上述脚本挂载到主相机对象上,确保玩家对象设置好对应的
Player标签 - 偏移参数
baseOffset可根据实际视角需求调整,Z值为负代表在玩家身后,Y值为正代表抬高视角 - 旋转平滑速度可根据游戏节奏调整,转90度的过程控制在0.5-1秒区间时,操作体验和原作的匹配度最高
内容的提问来源于stack exchange,提问作者Niaz Bin Siraj
相关产品推荐
相关产品推荐

