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

2D平台游戏平台未受作用力问题求助(附代码及截图)

2D平台游戏平台横向移动失效问题解决

我正在开发一款2D平台游戏,需要实现平台横向穿越屏幕的功能,但当前代码无法让平台移动。以下是相关代码及截图:

public GameObject plat;
public Vector2 pos;
private bool instantiated = false;

void Start()
{
    InvokeRepeating("Duplicate", 1.5f, 1.5f);
}

void Duplicate()
{
    if (!instantiated)
    {
        Debug.Log("Duplicated");
        GameObject newPlat = Instantiate(plat, new Vector2(pos.x, pos.y), Quaternion.identity);
        Rigidbody2D platbody = newPlat.GetComponent<Rigidbody2D>();
        platbody.AddForce(-transform.right * 5);
        instantiated = true;
    }
}

游戏Rigidbody2D设置截图

问题排查与修复

  • 单次生成限制导致无后续平台
    代码中instantiated = true后,InvokeRepeating触发的Duplicate方法只会执行一次,后续不会生成新平台,且首次生成的平台可能因推力不足或物理设置问题移动不明显。
  • 物理参数设置错误
    从截图的Rigidbody2D设置来看:
    • 必须确保Body Type为Dynamic,静态物体无法被外力推动
    • 检查Linear Drag(线性阻力),过高的阻力会直接抵消添加的推力
    • 禁止勾选Kinematic,运动学物体不受物理力影响
  • 修复代码及设置
    1. 移除单次生成限制,让平台重复生成:
      public GameObject plat;
      public Vector2 pos;
      
      void Start()
      {
          InvokeRepeating("Duplicate", 1.5f, 1.5f);
      }
      
      void Duplicate()
      {
          Debug.Log("Duplicated");
          GameObject newPlat = Instantiate(plat, new Vector2(pos.x, pos.y), Quaternion.identity);
          Rigidbody2D platbody = newPlat.GetComponent<Rigidbody2D>();
          // 增大推力值,确保突破阻力
          platbody.AddForce(-transform.right * 50);
      }
      
    2. 调整平台预制体的Rigidbody2D:
      • 设置Body Type为Dynamic
      • 将Linear Drag设为0~0.5之间的数值
      • 取消Kinematic勾选
    3. 可选:添加屏幕外销毁逻辑(附加到平台预制体):
      void Update()
      {
          // 计算屏幕左边界,超出后销毁平台
          float leftEdge = -Camera.main.orthographicSize * Camera.main.aspect - 2f;
          if (transform.position.x < leftEdge)
          {
              Destroy(gameObject);
          }
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 17:12:46