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

Unity:如何用Wheel Joint 2D限制车辆Z轴旋转,避免跳跃翻转?

解决横版汽车跑酷游戏中车辆跳跃翻转问题

我正在开发一款横版跳跃跑酷游戏,但玩家操控的是一辆汽车。我使用了Wheel Joint 2D组件,并且已经实现了跳跃功能。以下是我的移动代码:

void Update()
{
    movement = Input.GetAxis("Horizontal");

    if (Input.GetButtonDown("Jump") && IsGrounded())
    {
        carRb.velocity = new Vector2(carRb.velocity.x, jumpForce);
    }

    if (Input.GetButtonUp("Jump") && carRb.velocity.y > 0f)
    {
        carRb.velocity = new Vector2(carRb.velocity.x, carRb.velocity.y * 0.5f);
    }
}

private void FixedUpdate()
{
    backTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    frontTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    carRb.AddTorque(-movement * carTorque * Time.fixedDeltaTime);
}

目前代码运行正常,但当车辆高速行驶并跳跃时,会绕自身轴完全翻转,最终以头部着地且无法移动。因此我希望限制车辆Z轴的旋转角度,避免这种情况发生。


方法1:代码动态修正旋转角度

在FixedUpdate末尾加入旋转限制逻辑,空中时把车身倾斜角度锁在合理范围,落地后自动回正:

private void FixedUpdate()
{
    backTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    frontTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    carRb.AddTorque(-movement * carTorque * Time.fixedDeltaTime);

    // 限制Z轴旋转
    if (!IsGrounded())
    {
        // 将当前旋转转换为-180到180的标准范围
        float currentRot = Mathf.DeltaAngle(0, carRb.rotation);
        // 自定义允许的最大倾斜角度,可根据手感调整
        float maxTilt = 45f;

        if (Mathf.Abs(currentRot) > maxTilt)
        {
            // 计算目标角度,保持在允许范围内
            float targetRot = Mathf.Sign(currentRot) * maxTilt;
            // 平滑修正旋转,避免生硬跳转
            carRb.MoveRotation(Mathf.Lerp(carRb.rotation, targetRot, 0.1f));
            // 降低旋转角速度,阻止继续翻转
            carRb.angularVelocity *= 0.5f;
        }
    }
    else
    {
        // 落地时逐步回正到水平状态
        carRb.MoveRotation(Mathf.Lerp(carRb.rotation, 0, 0.2f));
    }
}

方法2:优化扭矩施加逻辑

空中时不给车身施加扭矩,只保留轮胎的动力输出,减少额外旋转力:

private void FixedUpdate()
{
    backTire.AddTorque(-movement * speed * Time.fixedDeltaTime);
    frontTire.AddTorque(-movement * speed * Time.fixedDeltaTime);

    // 仅在落地状态下给车身施加扭矩
    if (IsGrounded())
    {
        carRb.AddTorque(-movement * carTorque * Time.fixedDeltaTime);
    }
}

方法3:用物理关节约束旋转(最自然)

借助Unity的Angle Joint 2D组件,让物理引擎自动控制旋转范围:

  1. 给车辆GameObject添加Angle Joint 2D组件
  2. 创建一个空物体作为锚点(位置与车辆初始位置一致),将Angle Joint 2D的Connected Body设置为该空物体的Rigidbody2D(若锚点不需要移动,也可设为None使用世界锚点)
  3. 在Angle Joint 2D的参数面板中:
    • 将Angle设为0(对应车辆水平状态)
    • 勾选Enable Limits,设置Lower Angle Limit和Upper Angle Limit(例如-45和45)
    • 调整Motor Torque和Motor Speed参数,让车辆超出限制范围时能被自然拉回,数值需根据实际手感调试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:55:23