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

Unity中角色穿墙问题求助:使用Rigidbody移动仍穿墙

第一人称角色穿墙问题解决

我做了个带第一人称移动的简易角色,为了更好控制物理效果没用到CharacterController。角色的Rigidbody是非运动学状态,编辑器里碰撞矩阵设置都正确,但角色还是会穿墙。当前用的移动代码如下:

playerRb.MovePosition(transform.position + (transform.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime) + (transform.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime));

Rigidbody组件参数:质量1、拖拽0、角拖拽0.05,启用重力,非运动学,碰撞检测为离散,冻结X/Y/Z轴旋转。


问题根源

MovePosition是直接强制设置刚体位置,相当于瞬移,物理引擎没法实时处理碰撞检测,尤其是移动速度稍快时,很容易直接穿过碰撞体。

解决方法

换用物理引擎原生的移动方式,让引擎处理碰撞逻辑:

方法1:用AddForce(适合需要真实物理交互的场景)

Vector3 moveDir = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal");
moveDir.Normalize(); // 避免斜向移动时速度翻倍
playerRb.AddForce(moveDir * moveSpeed, ForceMode.Acceleration);

方法2:直接设置Velocity(精准控制移动速度)

Vector3 moveDir = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal");
moveDir.Normalize();
Vector3 targetVelocity = moveDir * moveSpeed;
// 保留Y轴的重力速度,只修改水平方向移动
targetVelocity.y = playerRb.velocity.y;
playerRb.velocity = targetVelocity;

额外优化

  • 把Rigidbody的碰撞检测模式改成「连续动态」,提升快速移动物体的碰撞精度;
  • 确保墙体的碰撞体是凸碰撞体,如果用Mesh Collider必须勾选「Convex」,否则非运动学刚体无法和它产生正确碰撞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:10:39