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

无限跑酷游戏玩家落于上下移动平台时弹跳及随平台左移问题求解

解决方案

问题根因

弹跳问题核心来自两个物理逻辑缺陷:

  • 移动平台直接修改transform.position移动,属于非物理驱动的"瞬移",物理引擎无法正确识别平台的运动状态,碰撞时会产生异常向上的挤压力,触发弹跳
  • 未同步玩家与平台的纵向运动,平台上下移动时与玩家碰撞体发生相对位移,触发物理碰撞的自动矫正力

具体修改步骤

1. 移动平台配置与代码修改

  • 给所有移动平台添加Rigidbody2D组件,参数设置如下:
    • Body Type设为Kinematic
    • 重力缩放设为0
    • 冻结Z轴旋转
    • Collision Detection设为Continuous
  • 给移动平台设置统一标签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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:48:04