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

Unity中如何让生成的立方体不碰撞并实现正确堆叠?

生成堆叠立方体时的重叠与物理弹跳问题

我有一个Cube预制体,想要生成多个立方体并按行列排列或堆叠放置。给立方体添加了Collider和Rigidbody组件后,位置计算出现问题。尝试通过检测重叠并重新调整位置来修复,但这个方法无效,生成后的立方体还会受到作用力被弹开。当前核心问题是生成时立方体出现重叠。

代码实现:

//spawn
//Vector3 offset = new Vector3(1.0f, 100f, 100f); 
List<GameObject> cubes = new List<GameObject>();

foreach (var item in cubesPrefabs)
{
    var mBox = Instantiate(box, parent.transform);

    Transform cubeTransform = mBox.GetComponent<Transform>();

    // Get references to the cube's collider and rigidbody
    Collider cubeCollider = mBox.GetComponent<Collider>();
    Rigidbody cubeRigidbody = mBox.GetComponent<Rigidbody>();

    // Add the cube to the list
    cubes.Add(mBox);

    // Calculate the scale required to match the desired size in meters
    Vector3 scale = new Vector3(((float)item.cLength / cubeTransform.localScale.x) ,
                                 ((float)item.cHeight / cubeTransform.localScale.y),
                                 ((float)item.cWidth / cubeTransform.localScale.z) );

    // Set the scale of the cube to match the desired size in meters
    cubeTransform.localScale = scale;

    Vector3 pos = new Vector3(item.cPosL, item.cPosH , item.cPosW );
    cubeTransform.localPosition = pos;

    Debug.Log("Look here. pos: " + pos.ToString() + " , scale: " + scale.ToString());
    // Check for collisions with all other cubes in the list
    for (int i = 0; i < cubes.Count - 1; i++)
    {
        // Get references to the collider and rigidbody of the other cube
        Collider otherCollider = cubes[i].GetComponent<Collider>();
        Rigidbody otherRigidbody = cubes[i].GetComponent<Rigidbody>();

        // Check if the two colliders are overlapping
        if (cubeCollider.bounds.Intersects(otherCollider.bounds))
        {
            // Calculate the direction and distance to move the cubes apart
            Vector3 direction = (cubeTransform.position - cubes[i].transform.position).normalized;
            float distance = Mathf.Abs(cubeCollider.bounds.min.x - otherCollider.bounds.max.x);

            // Move the cubes apart along the calculated direction and distance
            cubeRigidbody.MovePosition(cubeTransform.position + direction * distance / 2.0f);
            otherRigidbody.MovePosition(cubes[i].transform.position - direction * distance / 2.0f);
        }
    }
}

效果截图:

立方体重叠效果截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:28:21