Unity3D中Physic2D摩擦问题:跳跃并右移时角色粘墙
问题修复:跳跃+移动时角色粘墙
问题根源
你的Run()方法每帧都会强制覆盖刚体的X轴速度,哪怕角色已经碰到墙面,这会让角色持续向墙面施加移动力,最终出现"粘墙"的情况。另外,isGrounded状态没有正确维护,也会影响跳跃和移动的逻辑判断。
修复步骤
新增墙面层
在Unity编辑器中创建一个名为Wall的层,将场景中所有墙面物体的层设置为Wall。修改移动逻辑
更新Run()方法,当角色空中碰到墙面时,停止强制施加横向移动力,让物理引擎自然处理碰撞:
void Run() { bool isTouchingWall = playerCollider.IsTouchingLayers(LayerMask.GetMask("Wall")); // 地面上即使贴墙也能移动,空中碰墙则停止横向移动 bool shouldApplyMoveInput = !isTouchingWall || isGrounded; float horizontalVelocity = shouldApplyMoveInput ? vector2Move.x * playerSpeed : rb2D.velocity.x; Vector2 playerMovement = new Vector2(horizontalVelocity, rb2D.velocity.y); rb2D.velocity = playerMovement; // 优化跑步动画触发条件 animatorPlayer.SetBool("isRunning", shouldApplyMoveInput && Mathf.Abs(vector2Move.x) > 0.1f); }
- 正确维护接地状态
补充碰撞事件的处理逻辑,确保isGrounded状态准确:
private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Ground")) { isGrounded = true; animatorPlayer.SetBool("isGrounded", true); } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.layer == LayerMask.NameToLayer("Ground")) { isGrounded = false; animatorPlayer.SetBool("isGrounded", false); } }
- 补全缺失变量与优化跳跃逻辑
代码中缺失jumpForce和animatorPlayer的定义,同时优化跳跃逻辑避免速度叠加异常:
// 在类顶部添加缺失的序列化变量 [SerializeField] float jumpForce; [SerializeField] Animator animatorPlayer; // 优化跳跃方法 void OnJump(InputValue value) { if (isGrounded && value.isPressed) { // 直接设置Y轴速度,避免多次触发跳跃导致速度异常 rb2D.velocity = new Vector2(rb2D.velocity.x, jumpForce); animatorPlayer.SetBool("isIdling", false); isGrounded = false; } }
内容的提问来源于stack exchange,提问作者Đỗ Trọng Khoa
相关产品推荐
相关产品推荐

