如何检测随机生成的预制件的重叠

时间:2014-11-02 08:23:02

标签: c# arrays unity3d instantiation overlapping

我有一个随机生成的工作脚本:

PosX,PosY,ScaleX和ScaleY

我将随机生成的预制件放入并行阵列中。从中生成随机调整大小和定位的立方体。但是,由于它是随机生成的,我如何通过代码检测到重叠?如果有重叠,我怎么能删除它?

我需要帮助编写代码。我尝试过使用光线投射和OnTriggerEnter,但我对如何操作感到困惑。我也见过使用

Physics.CheckCapsule
Physics.CapsuleCastAll
Physics.CheckSphere
Bounds.Intersect

但我不知道该怎么做。

我不知道如何在数组上使用Physics.OverlapSphere。 我该怎么做。

void Detect_Collision_Two(int i) {
    bool isOverLapped = false;

    Collider[] platformsInRange = Physics.OverlapSphere(platformPrefabPosition[i], scaleX[i]/2);
    foreach(Collider col in platformsInRange) {
        if(col.gameObject == platformPrefab) {
            continue;
        }
        if 
    }


}

修改

尝试 这些是我尝试使用数学方法的尝试。检查中心位置并考虑平台的宽度和高度。然后使用该信息与其他平台进行比较。

第二种方法是使用OverlapSphere,但我不知道如何实现它。 请帮忙

void Platform_Position_Scale_Generator(int i) {

    posX[i] = Random.Range(minPosRange, maxPosRange + 1);
    posY[i] = Random.Range(minPosRange, maxPosRange + 1);
    posZ[i] = 0;

    scaleX[i] = Random.Range(minScaleRange, maxScaleRange + 1);
    scaleY[i] = 1;
    scaleZ[i] = 1;

}

void Platform_Generator(int i) {

    platformPrefabPosition[i].x = posX[i];
    platformPrefabPosition[i].y = posY[i];
    platformPrefabPosition[i].z = posZ[i];

    Instantiate(platformPrefab, platformPrefabPosition[i], Quaternion.identity);
    platformPrefab.transform.localScale = new Vector3(scaleX[i], 1, 1);


}

// Error with this
void Detect_Collision(int i) {

    for(int f = 0; f < i; f++) {
        for(int s = f + 1; s < i; s++) {
            bool xOverlap = (posX[s] > posX[f] && posX[s] < posX[f] + scaleX[i]) || (posX[f] > posX[s] && posX[f] < posX[s] + scaleX[i]);
            bool yOverlap = (posY[s] > posY[f] && posY[s] < posY[f] + scaleY[i]) || (posY[f] > posY[s] && posY[f] < posY[s] + scaleY[i]);

            if(xOverlap && yOverlap) {
                Debug.Log("xOverlap: " + xOverlap + " yOverlap: " + yOverlap);
            }
            else {
                //Debug.Log("xOverlap: " + xOverlap + " yOverlap: " + yOverlap);
            }
        }
    }

}

void Detect_Collision_Two(int i) {
    bool isOverLapped = false;

    Collider[] platformsInRange = Physics.OverlapSphere(platformPrefabPosition[i], scaleX[i]/2);
    foreach(Collider col in platformsInRange) {
        if(col.gameObject == platformPrefab) {
            continue;
        }
        if 
    }


}

1 个答案:

答案 0 :(得分:1)

您需要以对象位置中心为中心,界限范围作为半径来制作 overlapSphere 并检查所有如果与新对象边界相交,则此边界中的碰撞器

 bool isOverlapped = false;
 Bounds bounds = renderer.bounds;
 Collider[] cols = Physics.OverlapSphere(transform.position, bounds.extents.magnitude);
 foreach(Collider col in cols) {
     if (col.gameObject == gameObject) {
         continue; 
     }
     if (bounds.Intersects(col.gameObject.renderer.bounds)) {
         isOverlapped = true;
         break;
     }
 }

在此之后你可以使用 isOverlapped 布尔来销毁你的对象

 if(isOverlapped)
         Destroy (gameObject);