Unity 2D平台游戏角色卡入Tilemap墙体问题求助
Unity 2D角色卡入墙体问题解决方案
一、代码层面修复(核心)
问题根源是直接强制设置角色X方向速度,未考虑碰撞状态。修改移动逻辑,当触碰墙体且移动方向朝向墙时,禁止向该方向移动:
修改Update方法中的移动代码
private void Update() { float x = Input.GetAxis("Horizontal"); float targetXVelocity = x * movement_speed; // 触碰墙体时,禁止向墙的方向移动 if (isTouchingWall()) { bool isMovingTowardsWall = (transform.localScale.x > 0 && x > 0) || (transform.localScale.x < 0 && x < 0); if (isMovingTowardsWall) { targetXVelocity = 0; } } rb_player.velocity = new Vector2(targetXVelocity, rb_player.velocity.y); // 以下翻转、跳跃、动画代码保持不变 if(x > 0.01f) { transform.localScale = new Vector3(1, 1, 1); } else if(x < -0.01f) { transform.localScale = new Vector3(-1, 1, 1); } if(Input.GetKeyDown(KeyCode.Space) && isGrounded()) { jump(); } anim.SetBool("run", x != 0); anim.SetBool("jump", !isGrounded()); print("wall: "+isTouchingWall()); print("ground: "+isGrounded()); }
移除Awake中覆盖LayerMask的代码
避免覆盖Inspector面板的手动设置:
private void Awake() { rb_player = GetComponent<Rigidbody2D>(); anim = GetComponent<Animator>(); boxCollider = GetComponent<BoxCollider2D>(); // 删除以下两行 // groundLayer = LayerMask.GetMask("ground"); // wallLayer = LayerMask.GetMask("wall"); }
二、Tilemap碰撞体设置检查
确保墙体Tilemap的碰撞组件配置正确:
- 选中墙体Tilemap,确认
Tilemap Collider 2D组件的Used By Composite选项已勾选 - 将
Composite Collider 2D组件的Geometry Type设为Outlines(避免Tile边缘细碎碰撞导致卡墙) - 确保
Composite Collider 2D的Is Trigger未勾选
三、角色刚体设置优化
调整角色Rigidbody2D参数提升碰撞稳定性:
- 设置Body Type为
Dynamic(物理碰撞生效的前提) - 设置Collision Detection Mode为
Continuous(解决快速移动时的穿模问题) - 勾选Constraints中的Freeze Rotation Z(防止角色旋转导致碰撞异常)
内容的提问来源于stack exchange,提问作者Lavender Vampire
相关产品推荐
相关产品推荐

