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

Unity玩家角色跳跃异常:点击跳跃键后角色瞬移而非正常跳跃

Unity角色跳跃瞬移问题修复

问题根源

你的代码出现瞬移而非正常跳跃,核心原因有这几点:

  • 跳跃时直接覆盖整个Rigidbody速度向量,丢失水平移动速度的同时,超大的jump值让角色瞬间窜升
  • Update里强制把velocity的y轴设为0,打断了跳跃的物理运动过程
  • 地面检测用Trigger的逻辑不够严谨,容易出现误判
  • 条件判断用了按位与&,应该使用逻辑与&&

修复后的完整代码

private float speed = 10f;
private bool canJump = false;
private Rigidbody rb;
// 调整为合理的跳跃力数值
private float jumpForce = 5f;
private float movementX;
public bool isGrounded;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

private void OnMove(InputValue movementValue)
{
    Vector2 movementVector = movementValue.Get();
    movementX = movementVector.x;
}

void Update()
{
    // 仅修改水平速度,保留y轴的物理运动状态
    Vector3 horizontalMovement = new Vector3(movementX, 0f, 0f) * speed;
    rb.velocity = new Vector3(horizontalMovement.x, rb.velocity.y, horizontalMovement.z);

    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        canJump = true;
    }

    // 应用跳跃重力优化,实现更自然的手感
    if (rb.velocity.y < 0)
    {
        rb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
    }
    else if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.Space))
    {
        rb.velocity += Vector3.up * Physics.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
    }
}

// 改用碰撞检测判断地面,比Trigger更稳定
private void OnCollisionStay(Collision collision)
{
    if (collision.gameObject.CompareTag("ground"))
    {
        isGrounded = true;
    }
}

private void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.CompareTag("ground"))
    {
        isGrounded = false;
    }
}

private void FixedUpdate()
{
    if (canJump && isGrounded)
    {
        // 仅修改y轴速度,保留水平移动状态
        rb.velocity = new Vector3(rb.velocity.x, jumpForce, rb.velocity.z);
        // 也可以用AddForce实现:rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        canJump = false;
    }
}

关键修改说明

  1. 保留水平速度:修改velocity时仅替换x轴分量,不干扰y轴的物理运动,避免跳跃时丢失移动状态
  2. 调整跳跃逻辑:不再直接替换整个velocity,仅修改y轴速度;同时降低跳跃力数值,让跳跃符合物理规律
  3. 优化地面检测:改用OnCollisionStay/Exit替代Trigger,避免角色边角离开地面就误判为空中状态
  4. 启用重力优化:把你定义的fallMultiplier和lowJumpMultiplier逻辑加入Update,实现快速松键跳得低、下落更快的自然手感
  5. 修正逻辑运算符:把&改成&&,减少不必要的条件判断

内容的提问来源于stack exchange,提问作者The grassy Thegrassychespin Ch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:54:20