无限跑酷游戏玩家落于上下移动平台时弹跳及随平台左移问题求解
解决方案
问题根因
弹跳问题核心来自两个物理逻辑缺陷:
- 移动平台直接修改
transform.position移动,属于非物理驱动的"瞬移",物理引擎无法正确识别平台的运动状态,碰撞时会产生异常向上的挤压力,触发弹跳 - 未同步玩家与平台的纵向运动,平台上下移动时与玩家碰撞体发生相对位移,触发物理碰撞的自动矫正力
具体修改步骤
1. 移动平台配置与代码修改
- 给所有移动平台添加
Rigidbody2D组件,参数设置如下:- Body Type设为
Kinematic - 重力缩放设为0
- 冻结Z轴旋转
- Collision Detection设为
Continuous
- Body Type设为
- 给移动平台设置统一标签
MovingPlatform - 替换原有平台运动逻辑代码:
private int moveVertical; private Rigidbody2D platform_RB; void Start() { platform_RB = GetComponent<Rigidbody2D>(); moveVertical = Random.Range(1, 3); } // 物理相关操作统一放在FixedUpdate执行 void FixedUpdate() { // 纵向运动方向切换逻辑 if (transform.position.y < -2f) moveVertical = 1; else if (transform.position.y > 2f) moveVertical = 2; float ySpeed = moveVertical == 1 ? 5f : -5f; Vector2 targetPos = new Vector2( transform.position.x - 7f * Time.fixedDeltaTime, transform.position.y + ySpeed * Time.fixedDeltaTime ); // 用MovePosition移动,物理引擎会正确计算平台运动速度 platform_RB.MovePosition(targetPos); if (transform.position.x <= -20) Destroy(gameObject); }
2. 玩家逻辑修改
- 给玩家的
Rigidbody2D设置Collision Detection为Continuous - 玩家和平台使用的物理材质2D,弹力(Bounciness)统一设为0
- 补充玩家的运动同步逻辑,替换原有玩家代码:
private Rigidbody2D player_RB; private bool isOnMovingPlatform; private Rigidbody2D currentPlatformRB; void Awake() { player_RB = GetComponent<Rigidbody2D>(); } // 碰撞检测判断是否站在移动平台上 void OnCollisionStay2D(Collision2D other) { if (!other.gameObject.CompareTag("MovingPlatform")) return; // 只有碰撞法线向上才判定为站在平台顶部 foreach (ContactPoint2D contact in other.contacts) { if (contact.normal.y > 0.5f) { isOnMovingPlatform = true; currentPlatformRB = other.rigidbody; break; } } } void OnCollisionExit2D(Collision2D other) { if (other.gameObject.CompareTag("MovingPlatform")) { isOnMovingPlatform = false; currentPlatformRB = null; } } void Update() { // 跳跃输入检测放在Update保证响应准确 if (Input.GetMouseButtonDown(0)) { player_RB.velocity = new Vector2(player_RB.velocity.x, 20f); } } void FixedUpdate() { // 站在移动平台上时仅同步纵向速度,横向速度不受平台影响 if (isOnMovingPlatform && currentPlatformRB != null) { player_RB.velocity = new Vector2(player_RB.velocity.x, currentPlatformRB.velocity.y); } }
效果说明
修改后不需要将玩家设为平台子物体,平台横向移动不会影响玩家的X轴位置,纵向运动完全同步,不会再出现弹跳问题。
内容的提问来源于stack exchange,提问作者gw707
相关产品推荐
相关产品推荐

