Unity角色墙跳无法远离墙面的问题及代码修复请求
Unity角色墙跳问题修复方案
问题根源
- 原代码开头的
rb.velocity = new Vector2(dirX * movespeed, rb.velocity.y);会在每帧强制覆盖水平速度,导致墙跳时设置的水平方向被直接冲掉 - 墙跳的水平方向逻辑错误,用
rb.velocity.x -1无法精准控制远离墙面的方向
修复后的完整代码
void Update() { timer += Time.deltaTime; dirX = Input.GetAxisRaw("Horizontal"); dirY = Input.GetAxisRaw("Vertical"); // 提取墙滑状态,避免重复判断 bool isWallSliding = (IsWalledright() || IsWalledleft()) && (rb.velocity.y < 0) && !IsGrounded() && Mathf.Abs(dirX) > 0; // 只有不在墙滑状态时,才应用常规水平移动 if (!isWallSliding) { rb.velocity = new Vector2(dirX * movespeed, rb.velocity.y); } // 地面跳跃逻辑 if (Input.GetButtonDown("Vertical") && IsGrounded()) { rb.velocity = new Vector2(rb.velocity.x, dirY * jumpforce); } // 二段跳逻辑 if (Input.GetButtonDown("Vertical") && (rb.velocity.y != 0f) && doublejump && dirY > 0) { rb.velocity = new Vector2(rb.velocity.x, dirY * jumpforce); doublejump = false; } // 墙滑与墙跳处理 if (isWallSliding) { rb.velocity = new Vector2(rb.velocity.x, -slidingspeed); if (Input.GetButtonDown("Vertical")) { // 根据墙面位置计算远离方向:右墙向左跳,左墙向右跳 float wallJumpHorizontalDir = IsWalledright() ? -1f : 1f; // 设置墙跳的速度,水平方向用远离墙面的方向乘以移动速度(可自定义墙跳力度) rb.velocity = new Vector2(wallJumpHorizontalDir * movespeed, dirY * jumpforce); // 可选:墙跳后重置二段跳,让玩家能继续二段跳 doublejump = true; } } if (IsGrounded()) { doublejump = true; } UpdateAnimationState(); }
关键修改说明
- 避免速度覆盖:将常规水平移动的逻辑限制在非墙滑状态下,确保墙跳时设置的水平速度不会被每帧的移动代码覆盖
- 精准控制墙跳方向:通过
IsWalledright()和IsWalledleft()判断玩家当前贴的是左墙还是右墙,直接生成远离墙面的水平方向,彻底解决朝向墙面跳的问题 - 代码优化:把墙滑状态提取为单独变量,减少重复判断,提升代码可读性
- 手感优化(可选):墙跳后重置二段跳状态,让玩家在墙跳后仍能使用二段跳,操作更灵活
内容的提问来源于stack exchange,提问作者Zayd Ben Fathel
相关产品推荐
相关产品推荐

