You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#技术需求:3D横版BMX游戏中相机随玩家速度增加而远离

相机随玩家速度动态后移的实现方案

核心思路:通过获取玩家移动速度,动态调整相机与玩家的距离——速度越快,相机越靠后,同时保留原有的平滑跟随逻辑,不需要给相机添加Rigidbody组件。

可调节参数(直接在Unity Inspector面板修改)

  • baseDistance:玩家静止/低速时,相机与玩家的基础距离
  • maxDistance:玩家高速移动时,相机的最大后移距离
  • minSpeedThreshold:触发相机后移的最低速度(低于此值时用基础距离)
  • maxSpeedThreshold:达到此速度时,相机切换为最大距离

修改后的完整代码

private Vector3 _localOffset; // 用玩家局部空间定义偏移,适配转向
[SerializeField] private Transform target;
[SerializeField] private float smoothTime;
[SerializeField] private float baseDistance = 5f;
[SerializeField] private float maxDistance = 10f;
[SerializeField] private float minSpeedThreshold = 2f;
[SerializeField] private float maxSpeedThreshold = 8f;

private Vector3 _currentVelocity = Vector3.zero;
private Rigidbody _playerRb; // 玩家的刚体组件

private void Awake()
{
    // 获取玩家的Rigidbody(若玩家用CharacterController,替换为GetComponent<CharacterController>())
    _playerRb = target.GetComponent<Rigidbody>();
    // 初始化局部偏移:根据你的游戏坐标系调整,示例为玩家上方2单位、后方baseDistance单位
    _localOffset = new Vector3(0, 2, -baseDistance);
}

private void LateUpdate()
{
    // 获取玩家当前移动速度的大小
    float currentSpeed = _playerRb.velocity.magnitude;
    
    // 将当前速度映射为0-1的比例,用于平滑过渡相机距离
    float distanceRatio = Mathf.InverseLerp(minSpeedThreshold, maxSpeedThreshold, currentSpeed);
    // 限制比例范围,避免超出设定的距离区间
    distanceRatio = Mathf.Clamp01(distanceRatio);
    
    // 计算当前相机应保持的后向距离
    float currentDistance = Mathf.Lerp(baseDistance, maxDistance, distanceRatio);
    // 更新局部偏移的后向数值
    Vector3 adjustedLocalOffset = new Vector3(_localOffset.x, _localOffset.y, -currentDistance);
    
    // 将局部偏移转换为世界空间位置,确保相机始终在玩家后方
    Vector3 targetPosition = target.position + target.TransformDirection(adjustedLocalOffset);
    
    // 保留原有的平滑跟随逻辑
    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref _currentVelocity, smoothTime);
}

关键细节说明

  • 局部空间偏移:确保玩家转向时,相机始终保持在玩家后方,不会出现方向错乱
  • 平滑过渡:用Mathf.InverseLerp和Mathf.Lerp实现速度到相机距离的平滑映射,避免突兀的视角变化
  • 适配不同玩家控制器:如果玩家用CharacterController,只需替换速度获取方式为_characterController.velocity.magnitude,并修改Awake中的组件获取逻辑

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:15:50