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

如何实现《反恐精英:全球攻势》风格的Weapon Bobbing效果?

CSGO风格武器摇晃(Weapon Bobbing)实现方案

原代码的核心问题是未与移动动作同步、摇晃相位单一、缺少平滑过渡,以下是修正后的实现思路和代码:

原代码的关键问题

  • 用全局时间Time.timeSinceLevelLoad驱动摇晃,导致摇晃和玩家移动节奏完全脱节
  • X/Y轴使用同相位的正弦函数,摇晃动作僵硬不自然
  • 静止时的处理逻辑无效,没有平滑回归初始位置
  • 未区分移动速度(走/跑)对摇晃幅度、速度的影响

改进后的实现代码

// 可调整的参数
public float walkBobSpeed = 14f;
public float runBobSpeed = 20f;
public float walkBobAmount = 0.05f;
public float runBobAmount = 0.1f;
public float smoothFactor = 8f; // 摇晃过渡的平滑系数

private Vector3 originalWeaponPos;
private float bobCycle; // 基于移动的循环变量,而非全局时间
private CharacterController controller; // 假设你用CharacterController控制移动

private void Start()
{
    originalWeaponPos = transform.localPosition;
    controller = GetComponent<CharacterController>();
}

private void Update()
{
    WeaponBobbing();
}

private void WeaponBobbing()
{
    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");
    
    // 只有在移动且触地时才触发摇晃
    if ((Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) && controller.isGrounded)
    {
        // 根据移动速度选择对应的摇晃参数
        bool isRunning = Input.GetKey(KeyCode.LeftShift);
        float bobSpeed = isRunning ? runBobSpeed : walkBobSpeed;
        float bobAmount = isRunning ? runBobAmount : walkBobAmount;
        
        // 基于时间和移动速度累加循环值,让摇晃和脚步同步
        bobCycle += Time.deltaTime * bobSpeed;
        
        // X和Y轴用不同相位的三角函数,模拟自然的走路姿势
        float xBob = Mathf.Sin(bobCycle) * bobAmount;
        float yBob = Mathf.Cos(bobCycle * 2) * bobAmount * 0.5f; // Y轴频率翻倍,幅度减半更真实
        
        // 计算目标位置并平滑过渡
        Vector3 targetPos = originalWeaponPos + new Vector3(xBob, yBob, 0);
        transform.localPosition = Vector3.Lerp(transform.localPosition, targetPos, Time.deltaTime * smoothFactor);
    }
    else
    {
        // 静止时平滑回归初始位置
        if (transform.localPosition != originalWeaponPos)
        {
            transform.localPosition = Vector3.Lerp(transform.localPosition, originalWeaponPos, Time.deltaTime * smoothFactor);
        }
        // 重置循环变量,避免下次移动时摇晃相位混乱
        bobCycle = 0f;
    }
}

核心优化点

  • 移动同步:用bobCycle基于移动状态累加,替代全局时间,让摇晃和脚步节奏匹配
  • 自然相位:X轴用Sin,Y轴用Cos且调整频率/幅度,模拟真实走路时的手臂摆动
  • 速度区分:走路和跑步使用不同的摇晃速度、幅度,贴合CSGO的手感
  • 平滑过渡:用Vector3.Lerp处理移动开始/结束时的摇晃变化,避免生硬跳变
  • 触地判断:只有在角色触地时才触发摇晃,避免空中、跳跃时的不合理摇晃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:12:49