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

Unity角色移动跳跃问题:走下边缘时重力异常过大

问题:角色走下平台边缘时重力异常(下落过快)

原代码

void UpdateMovement()
{
    Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    targetDir.Normalize();

    currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);

    if (controller.isGrounded)
    {
        velocityY = -gravity;
    }

    // jump
    if (controller.isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
        velocityY = jumpForce;
    }
    // sprint
    if (Input.GetKey(KeyCode.LeftShift))
    {
        velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * sprintSpeed + Vector3.up * velocityY;
    }
    else
    {
        velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * walkSpeed + Vector3.up * velocityY;
    }

    velocityY -= gravity * Time.deltaTime;
    Debug.Log(velocityY);

    controller.Move(velocity * Time.deltaTime);
}

问题描述

移动和跳跃功能正常,但角色未跳跃直接走下平台边缘时,下落速度异常快——跳跃时重力表现符合预期,但走下边缘时重力始终保持默认值15,导致下落速度失控。

问题原因

核心问题在velocityY的初始化和重力叠加逻辑:

  • 角色在地面时,你把velocityY设为-gravity(也就是-15)
  • 当角色离开平台,isGrounded变为false,这个初始化逻辑不再执行,但后续每帧都会执行velocityY -= gravity * Time.deltaTime,相当于从-15开始持续叠加向下的速度,自然下落极快

修复方案

调整velocityY的处理逻辑,让角色离开平台时从接近0的垂直速度开始累积重力:

void UpdateMovement()
{
    Vector2 targetDir = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    targetDir.Normalize();

    currentDir = Vector2.SmoothDamp(currentDir, targetDir, ref currentDirVelocity, moveSmoothTime);

    if (controller.isGrounded)
    {
        // 地面时将垂直速度设为极小负值,避免悬空时初始速度过大
        velocityY = -0.1f;
        
        // 跳跃逻辑合并到地面判断内,结构更清晰
        if (Input.GetKeyDown(KeyCode.Space))
        {
            velocityY = jumpForce;
        }
    }
    else
    {
        // 仅当悬空时叠加重力,避免地面时重复累积
        velocityY -= gravity * Time.deltaTime;
    }

    // 简化 sprint 速度判断
    float moveSpeed = Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : walkSpeed;
    velocity = (transform.forward * currentDir.y + transform.right * currentDir.x) * moveSpeed + Vector3.up * velocityY;

    controller.Move(velocity * Time.deltaTime);
}

修复说明

  1. 地面状态下,velocityY不再设为-gravity,而是一个接近0的极小负值,保证角色离开平台时初始下落速度很慢,之后逐渐被重力加速
  2. 把重力叠加逻辑移到else分支,只有角色悬空时才会持续叠加重力,避免地面时重复修改velocityY
  3. 跳跃逻辑合并到地面判断内,代码结构更紧凑,减少冗余判断

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:01:05