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

Unity实现玩家左右移动时相机平滑倾斜效果的方法

实现平滑的相机倾斜效果(基于移动输入)

要解决倾斜突兀的问题,核心是用基于时间的平滑过渡代替直接赋值,以下是具体实现步骤和代码:

核心思路

先根据移动输入计算相机的目标倾斜角度,再通过Mathf.Lerp或Mathf.SmoothDamp让当前角度渐进趋近目标值,同时用Time.deltaTime确保效果不受帧率波动影响,实现自然的过渡。

具体实现代码

创建一个挂载在相机上的C#脚本:

using UnityEngine;

public class SmoothCameraTilt : MonoBehaviour
{
    [SerializeField] private float maxTiltAngle = 15f; // 相机最大倾斜角度
    [SerializeField] private float smoothSpeed = 6f; // 平滑过渡速度,值越大响应越快

    private float currentTilt;

    void Update()
    {
        // 获取水平移动输入(对应A/D键或左右箭头)
        float horizontalInput = Input.GetAxis("Horizontal");

        // 计算目标倾斜角度:将输入值映射到正负最大倾斜范围
        float targetTilt = horizontalInput * maxTiltAngle;

        // 用Lerp实现平滑过渡,Time.deltaTime保证帧率无关
        currentTilt = Mathf.Lerp(currentTilt, targetTilt, smoothSpeed * Time.deltaTime);

        // 应用倾斜旋转(绕Z轴)
        transform.localRotation = Quaternion.Euler(0, 0, currentTilt);
    }
}

可选优化方案

如果想要更丝滑的减速效果,可以用Mathf.SmoothDamp替代Lerp,调整后的代码片段:

private float tiltVelocity; // 新增变量存储平滑速度

void Update()
{
    // ... 前面的输入和目标角度计算不变

    // 用SmoothDamp实现带加速度的平滑过渡
    currentTilt = Mathf.SmoothDamp(currentTilt, targetTilt, ref tiltVelocity, 0.1f);
    
    // ... 应用旋转不变
}

注意事项

  • 若相机是玩家对象的子物体,务必使用localRotation,避免父物体的旋转影响倾斜效果;
  • 可根据需求调整maxTiltAngle(倾斜幅度)和smoothSpeed(响应速度);
  • 如果你的移动输入不是来自Input.GetAxis("Horizontal"),替换成角色实际的水平移动方向分量即可(比如角色控制器的moveDirection.x)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:12:42