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

Unity中切换Player与Ball时无法传递Rigidbody2D速度求助

解决Unity变形时Rigidbody2D速度传递失效问题

问题出在你先禁用对象再读取速度的顺序上:当调用SetActive(false)时,目标对象的Rigidbody2D会被立即停用,此时读取它的velocity会返回Vector2.zero,导致速度传递完全失效。

调整代码逻辑,先读取速度,再禁用对象,就能解决这个问题。修改后的核心代码如下:

void Update()
{
    // 切换变形
    if (Input.GetKeyDown(KeyCode.F))
    {
        if (playerActive)
        {
            playerActive = false;
            // 先读取玩家的速度
            Vector2 playerVelocity = playerRB.velocity;
            
            // 激活球体,禁用玩家
            ball.SetActive(true);
            player.SetActive(false);
            
            // 传递位置和速度
            ball.transform.position = player.transform.position;
            ballRB.velocity = playerVelocity;
        }
        else
        {
            playerActive = true;
            // 先读取球体的速度
            Vector2 ballVelocity = ballRB.velocity;
            
            // 激活玩家,禁用球体
            player.SetActive(true);
            ball.SetActive(false);
            
            // 传递位置和速度
            player.transform.position = ball.transform.position;
            playerRB.velocity = ballVelocity;
        }
    }

    // 玩家移动逻辑不变
    if (playerActive)
    {
        moveVelocity = 0;

        if (Input.GetKeyDown(KeyCode.W))
        {
            if (grounded)
            {
                playerRB.velocity = new Vector2(playerRB.velocity.x, jumpHeight);
            }
        }

        if (Input.GetKey(KeyCode.A))
        {
            moveVelocity = -speed;
        }
        if (Input.GetKey(KeyCode.D))
        {
            moveVelocity = speed;
        }

        playerRB.velocity = new Vector2(moveVelocity, playerRB.velocity.y);
    }
}

另外补充两个你代码里的小问题,避免后续出现其他bug:

  • OnTriggerEnter2D和OnTriggerExit2D需要接收Collider2D参数,否则Unity会忽略无参数的版本,无法正确触发:
    void OnTriggerEnter2D(Collider2D other)
    {
        grounded = true;
    }
    void OnTriggerExit2D(Collider2D other)
    {
        grounded = false;
    }
    
  • 确保Player和Ball的Rigidbody2D都是Dynamic类型,并且没有勾选Sleeping Mode为Never Sleep,否则速度传递后可能不会立即生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:10:32